《劍指offer》數組中重複的數字,《劍指offer》數組
【 聲明:著作權,轉載請標明出處,請勿用於商業用途。 聯絡信箱:libin493073668@sina.com】
題目連結:http://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
題目描述
在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那麼對應的輸出是重複的數字2或者3。
思路
我們從頭到尾掃描這個數組,首先看第i位的數字x是否等於i,不等則把x與a[x]交換,然後繼續這個操作直到新的x等於i
如果此時x與a[x]相等,那麼這就是一個重複的值。
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 falsebool duplicate(int num[], int len, int* duplication){if(len==0)return false;for(int i = 0; i<len; i++){while(num[i]!=i){if(num[i]==num[num[i]]){*duplication = num[i];return true;}swap(num[i],num[num[i]]);}}return false;}};
著作權聲明:本文為博主原創文章,如果轉載,請註明出處