劍指offer3--陣列中重複的數字
阿新 • • 發佈:2019-02-02
連結:https://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8
來源:牛客網
在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數字。 例如,如果輸入長度為7的陣列{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。
思路:
雜湊表儲存
class Solution { public: // Parameters: // numbers: an array of integers // length: the length of array numbers // duplication: (Output) the duplicated number in the array number // Return value: true if the input is valid, and there are some duplications in the array number // otherwise false bool duplicate(int numbers[], int length, int* duplication) { int save[26]={0}; bool flag=false; for(int i=0;i<26;i++) save[i]=-1; for(int i=0;i<length;i++){ if(save[numbers[i]]==-1) save[numbers[i]]=i; else{ flag=true; *duplication=numbers[i]; break; } } if(flag) return true; else return false; } };
還有思路:
- 排序,然後找重複的
- 0~n-1.如果沒有重複的,應該0的下標是0,1的下標是1,。。。。n-1的下標是n-1.
不斷交換a[0]和a[a[0]]的值。。。。
直到發現a[i]=a[a[i]];
很厲害的方法,想不出來。。。