題目描述
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
解法
1.哈希表(需要使用額外空間)
import java.util.*;
public class Solution {
public boolean duplicate(int numbers[],int length,int [] duplication) {
if(length < 2){
return false;
}
Map<Integer,Integer> map = new HashMap<Integer,Integer> ();
for(int i:numbers){
if(!map.containsKey(i)){
map.put(i,1);
}
else{
duplication[0] = i;
return true;
}
}
return false;
}
}
2.轉化爲下標(不使用額外空間)
import java.util.*;
public class Solution {
public boolean duplicate(int numbers[], int length, int[] duplication) {
boolean[] k = new boolean[length];
for (int i = 0; i < k.length; i++) {
if (k[numbers[i]] == true) {
duplication[0] = numbers[i];
return true;
}
k[numbers[i]] = true;
}
return false;
}
}