(劍指offer)陣列中重複的數字
阿新 • • 發佈:2018-12-09
時間限制:1秒 空間限制:32768K 熱度指數:164725
本題知識點: 陣列
題目描述
在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數字。 例如,如果輸入長度為7的陣列{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
import java.util.*;
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 || numbers.length == 0){
return false;
}
HashSet<Integer>set = new HashSet<Integer>();
for(int i = 0; i < numbers. length; i++){
if(!set.add(numbers[i])){
duplication[0] = numbers[i];
return true;
}
}
return false;
}
}