題目描述
在一個長度爲n的數組裏的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度爲7的數組{2,3,1,0,2,5,3},那麼對應的輸出是重複的數字2或者3。
三種方法的代碼分別是:
常規思想:
1.一個個比較,重複即就是相等,則輸出複雜度o(n平方);
public static int duplicate(int numbers[],int length) {
if(numbers==null||length<1){
return -1;
}
int count=0;
for(int i=0;i<length;i++){
for(int j=1;j>i;j++){
if(numbers[i]==numbers[j]){
count=i;
break;
}
}
}
return numbers[count];
}
2.巧妙的字符串索引,複雜度o(n)
public static boolean duplicate(int numbers[],int length,int [] duplication) {
//複雜度o(n):思想巧妙的根據Java中字符串中的位置索引不同
//最笨的方法就是一個個對比,複雜度o(n平方);還有一個就是使用HashMap來統計字符出現的次數
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length; i++){
sb.append(numbers[i] + "");//將數組轉化爲字符串
}
for(int j = 0; j < length; j++){
//將數組轉化爲字符串,用字符串的出現字符的索引位置不同來判斷存在重複的字符
if(sb.indexOf(numbers[j]+"") != sb.lastIndexOf(numbers[j]+"")){
duplication[0] = numbers[j];
return true;
}
}
return false;
}
3.藉助HashMap,出現次數存放在value中。複雜度o(n)
public static int duplicate(int numbers[],int length){
int result=0;
HashMap<String,Integer> map=new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
int index=1;
if(map.containsKey(numbers[i]+"")){
index++;
map.put(numbers[i]+"", index);
result=numbers[i];
break;
}else{
map.put(numbers[i]+"", index);
}
}
return result;
}
public static void main(String[] args) {
int a[]={2,3,1,0,2};
System.out.println(duplicate(a,5));
}