劍指offer____陣列中重複的數字
阿新 • • 發佈:2018-11-15
在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數字。 例如,如果輸入長度為7的陣列{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
解法一:原地尋找法
class Solution { public: bool duplicate(int numbers[], int length, int* duplication) { if(numbers == NULL || length < 0) return false; for(int i=0; i<length; ++i) { while(numbers[i] != i) { if(numbers[i] == numbers[numbers[i]]) { *duplication = numbers[i]; return true; } int tmp = numbers[i]; numbers[i] = numbers[tmp]; numbers[tmp] = tmp; } } return false; }
解法二:位運算map
class Solution { public: bool duplicate(int numbers[], int length, int* duplication) { if(numbers == NULL || length <= 0) return false; int n = (length+7)&~7; char *repeat = new char[n]; //用於查重的陣列 //初始化用於查重的陣列 for (int i = 0; i < n; ++i) repeat[i] = 0; bool flag = false; //初始化為沒有找到 for(int i = 0; i < length; ++i){ //引數的合法性檢查 if (numbers[i] < 0 || numbers[i] > length-1) return false; if(repeat[numbers[i]/8] & 1<<numbers[i]%8){ //取餘高於移位高於按位與 flag = true; *duplication = numbers[i]; break; } repeat[numbers[i]/8] |= 1<<numbers[i]%8; } delete[] repeat; //格外注意!!!需要釋放申請的記憶體空間 return flag; } };
解法三:雜湊
class Solution{ public: bool duplicate(int numbers[], int length, int* duplication) { if(numbers == NULL || length <= 0) return false; int *buckets = (int *)malloc(sizeof(int)*length); if(buckets == NULL) return false; memset(buckets,0,sizeof(int)*length); for(int i = 0; i < length; i++) { buckets[numbers[i]]++; } for(int pos = 0; pos < length; pos++) { if(buckets[pos] > 1) { *duplication = pos; return true; } } free(buckets); buckets = NULL; return false; } };