C ++中数组中非重复(唯一)元素的乘积
给我们一个重复或重复元素的数组,任务是查找给定数组中所有不重复或不同的元素的乘积并显示结果。
示例
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; //计算非重复元素乘积的函数 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