題目描述
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
題目鏈接:牛客網
解題思路
要求時間複雜度 O(N),空間複雜度 O(1)。因此不能使用排序的方法,也不能使用額外的標記數組。
對於這種數組元素在 [0, n-1] 範圍內的問題,可以將值爲 i 的元素調整到第 i 個位置上進行求解。本題要求找出重複的數字,因此在調整過程中,如果第 i 位置上已經有一個值爲 i 的元素,就可以知道 i 值重複。
以 (2, 3, 1, 0, 2, 5) 爲例,遍歷到位置 4 時,該位置上的數爲 2,但是第 2 個位置上已經有一個 2 的值了,因此可以知道 2 重複。
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 這裏要特別注意~返回任意重複的一個,賦值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean 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[0] = numbers[i];
return true;
}
swap(numbers, i, numbers[i]);
}
}
return false;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}