C++ 中陣列中唯一元素,所有元素出現 k 次,只有一個例外


我們有一個數組 A。A 中所有元素都出現了 m 次,但只有一個元素只出現一次。我們需要找到這個唯一的元素。

所以,如果輸入類似 A = [6, 2, 7, 2, 2, 6, 6],m = 3,那麼輸出將是 7。

為了解決這個問題,我們將遵循以下步驟:

  • INT_SIZE := 整型變數大小的 8 倍
  • 定義一個大小為 INT_SIZE 的陣列 count,並填充 0
  • 初始化 i := 0,當 i < INT_SIZE 時,更新(i 加 1),執行:
    • 初始化 j := 0,當 j < size 時,更新(j 加 1),執行:
      • 如果 (arr[j] AND 2^i) 不等於 0,則:
        • count[i] := count[i] + 1
      • res := 0
    • 初始化 i := 0,當 i < INT_SIZE 時,更新(i 加 1),執行:
      • res := res + ((count[i] mod m) * 2^i)
    • 返回 res

讓我們看看下面的實現,以更好地理解:

示例(C++)

 線上演示

#include <bits/stdc++.h>
using namespace std;
int selectUnique(unsigned int arr[], int size, int m){
   int INT_SIZE = 8 * sizeof(unsigned int);
   int count[INT_SIZE];
   memset(count, 0, sizeof(count));
   for(int i = 0; i < INT_SIZE; i++)
      for(int j = 0; j < size; j++)
         if((arr[j] & (1 << i)) != 0)
            count[i] += 1;
   unsigned res = 0;
   for(int i = 0; i < INT_SIZE; i++)
      res += (count[i] % m) * (1 << i);
   return res;
}
main(){
   unsigned int arr[] = { 6, 2, 5, 2, 2, 6, 6 };
   int size = sizeof(arr) / sizeof(arr[0]);
   int m = 3;
   cout << selectUnique(arr, size, m);
}

輸入

{ 6, 2, 5, 2, 2, 6, 6 }

輸出

5

更新於: 2020-08-27

354 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.