題目描述:
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
思路:
- 先將數組排序
- 再遍歷數組,查看數組相鄰的數是否重複,若重複,則返回即可。
代碼:
package offer01;
import java.util.Arrays;
public class TestNo50 {
public static void main(String[] args) {
int[] a = {2,4,3,0,4};
int[] b = new int[1];
System.out.println(new TestNo50().duplicate(a,5,b));
}
public boolean duplicate(int numbers[],int length,int [] duplication) {
if(numbers == null || length ==0){
return false;
}
Arrays.sort(numbers);
for(int i = 0;i<numbers.length-1;i++){
if(numbers[i] == numbers[i+1]){
duplication[0] = numbers[i];
return true;
}
}
return false;
}
}