《劍指offer》數組中重複的數字,《劍指offer》數組

來源:互聯網
上載者:User

《劍指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;}};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.