題目
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
思路
遍歷整個數組,對於每個元素,把下標爲這個元素的位置上的元素加上數組的長度,表明這個位置的元素已經出現過,這樣,當對某個下標進行疊加長度之前,如果發現這個下標對應的元素已經大於或者等於數組的長度,說明這個下標已經被疊加過,也即這個元素已經重複了。
參考代碼
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
for (int i = 0; i < length; ++i) {
if (numbers[numbers[i] % length] >= length) {
*duplication = numbers[i] % length;
return true;
} else {
numbers[numbers[i] % length] += length;
}
}
return false;
}
};