找出數組中唯一的重複元素

來源:互聯網
上載者:User
數組a[N],1至N-1這N-1個數存放在a[N]中,其中某個數重複一次。找出這個數
void xor_findDup1(int *a,int N){//方法一:求和int tmp1 = 0;int tmp2 = 0;for(int i = 0;i < N - 1; ++i){//tmp1為1...N-1的和,tmp2為數組所有元素的和tmp1 += (i + 1);tmp2 += a[i];}tmp2 += a[N-1];printf("%d\n",tmp2 - tmp1);}void xor_findDup2(int *a,int N){//方法二:異或法int i;int result = 0;for(i = 0;i < N;++i){result ^= a[i];}for(i = 1;i < N;++i){result ^= i;}printf("%d\n",result);}#define sum(x) ((x)((x)+1)/2))void xor_findDup3(int *a,int N){//方法三(a):位元影像法int *arrayflag = (int*)malloc(N * sizeof(int));int i = 1;while(i < N){arrayflag[i] = false;++i;}for(i = 0;i < N; ++i){if( arrayflag[a[i]] == false)arrayflag[a[i]] = true;else{printf("%d\n",a[i]);return ;}}}int FindMoreInteger1(int *a,int N){//方法三(b):hashint i;for(i = 0; i < N; ++i){if( a[i] > 0){if(a[a[i]] > 0){a[a[i]] = -a[a[i]];}elsereturn -a[i];}else{if(a[-a[i]] > 0){a[-a[i]] = -a[-a[i]];}else{return -a[i];}}}}int FindMoreInteger2(int *a,int N){//方法四:尋找環的進入點(重複元素)int x,y;x = y = 0;do{x = a[a[x]];    //x一次走兩步y = a[y];       //y一次走一步}while(x != y);     //相遇點x = 0;do{x = a[x];y = a[y];}while(x != y);    //尋找進入點return x;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.