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

更新於: 20-Dec-2019

160 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.