在 C++ 中查詢與其他陣列元素頻率不同的元素
假設我們有一個包含 N 個數字的陣列,其中陣列中的每個元素都出現相同次數(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
示例
讓我們看看以下實現以獲得更好的理解:
#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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP