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;
//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
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP