반복되거나 중복되는 요소의 배열이 주어지며 주어진 배열에서 반복되지 않거나 구별되는 모든 요소의 곱을 찾아 결과를 표시하는 것이 작업입니다.
예시
Input-: arr[] = {2, 1, 1, 2, 3, 4, 5, 5 }
Output-: 120
Explanation-: Since 1, 2 and 5 are repeating more than once so we will take them into
consideration for their first occurrence. So result will be 1 * 2 * 3 * 4 * 5 = 120
Input-: arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4 }
Output-: 32400
Explanation-: Since 10 and 4 are repeating more than once so we will take them into consideration
for their first occurrence. So result will be 1 * 10 * 9 * 4 * 2 * 45 = 32400 아래 프로그램에서 사용된 접근 방식은 다음과 같습니다. -
- 배열에 중복 요소 입력
- 더 나은 접근 방식을 위해 배열 요소를 오름차순으로 정렬하여 어떤 배열 요소가 반복되는지 확인하고 제품에 대해 고려하지 않도록 합니다.
- 배열에서 모든 고유한 요소를 찾고 결과를 저장하여 계속 곱합니다.
- 배열에 있는 모든 개별 요소의 곱으로 최종 결과를 표시합니다.
알고리즘
Start
Step 1-> Declare function to find the product of all the distinct elements in an array
int find_Product(int arr[], int size)
Declare and set int prod = 1
Create variable as unordered_set<int> s
Loop For i = 0 and i < size and i++
IF s.find(arr[i]) = s.end()
Set prod *= arr[i]
Call s.insert(arr[i])
End
End
return prod
Step 2 -: In main()
Declare and set int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 }
Calculate the size of an array int size = sizeof(arr) / sizeof(int)
Call find_Product(arr, size)
Stop 예시
include <bits/stdc++.h>
using namespace std;
//function that calculate the product of non-repeating elements
int find_Product(int arr[], int size) {
int prod = 1;
unordered_set<int> s;
for (int i = 0; i < size; i++) {
if (s.find(arr[i]) == s.end()) {
prod *= arr[i];
s.insert(arr[i]);
}
}
return prod;
}
int main() {
int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 };
int size = sizeof(arr) / sizeof(int);
cout<<"product of all non-repeated elements are : "<<find_Product(arr, size);
return 0;
} 출력
product of all non-repeated elements are : 120