已排序陣列的絕對不同計數?


在本部分中,我們將瞭解如何計算絕對值不同的元素有多少個?假設陣列中有幾個元素,如 {5, 5, 6, -5, 8, 2, -2, 1},所以有 8 個元素。但有 5 個不同的元素 {5, 6, 8, 2, 1}。-5 和 5 不被視為不同的,因為它們的絕對值相同。

為了解決這個問題,我們將使用 Set 資料結構。在 set 中不允許有重複的元素。當我們向 set 中插入項時,我們將僅推送絕對值。

演算法

absoluteDistinctCount(arr)

begin
   define set s;
   for each element e in arr, do
      insert |e| into s
   done
   return the number of elements of s
end

示例

 線上例項

#include<iostream>
#include<set>
#include<cmath>
using namespace std;
int absoluteDistinctCount(int arr[], int n){
   set<int> s;
   for(int i = 0; i<n; i++){
      s.insert(abs(arr[i])); //insert the absolute value
   }
   return s.size();
}
main() {
   int arr[] = {5, 5, 6, -5, 8, 2, -2, 1};
   int n = (sizeof(arr))/(sizeof(arr[0]));
   cout << "Absolute Distinct Count: " << absoluteDistinctCount(arr, n);
}

輸出

Absolute Distinct Count: 5

更新於:2019-07-30

117 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.