PHP a[n+1]共有n+1個數,數值範圍是1~n,a中有1個數重複,其他各不相同,找出這個重複的數

來源:互聯網
上載者:User
 1 <?php 2     #a[n+1]共有n+1個數,數值範圍是1~n,a中有1個數重複,其他各不相同,找出這個相同的數 3      4     #第一種方法,利用 a數組的和減去1+2+3+...+n的和,得到的結果就是重複數字 5     function get_dup($a) { 6         $size = count($a); 7         $suma = 0; 8         $sumn = 0; 9         for ($i = 0; $i < $size; $i++) {10             $suma += $a[$i];11             $sumn += $i;12         }13 14         return $suma - $sumn;15     }16 17     #第二種方法,利用異或18     #異或的性質: A xor A = 0; 0 xor A = A;19     #解析:假設重複的數是A,除了A以外的1~n的異或值為B,則對數組a所有數進行異或,可以得到 A xor A xor B = B20     #對於1~n的各不相同的n個數,對他們進行異或的值是 A xor B21     #對上述兩步得到的值進行異或有 (A xor A xor B) xor (A xor B) = A,這樣就求出了A22     function get_dup_xor($a) {23         $x = $a[0];24         for ($i = 1; $i < count($a); $i++) {25             $x ^= $a[$i] ^ $i;26         }27 28         return $x;29     }30 31     #第三種方法,使用bitmap32     function get_dup_bitmap($a) {33         $bitmap = array();34         for ($i = 0; $i < count($a); $i++) {35             if (!isset($bitmap[$a[$i]])) {36                 $bitmap[$a[$i]] = 1;37             } else {38                 return $a[$i];39             }40         }41     }42 43     #第四種方法,利用修改數組內值44     #這種方法在數組以0開頭的時候會有問題,因為a[0]=0,下次還是跳到a[0] = null,直接就把0當重複的輸出了45     #當然了,按照題意不可能以0開頭46     function get_dup_mod($a) {47         $i = 0;48         while ($i < count($a)) {49             if ($a[$i] == null) {50                 return $i;51             }52             $j = $i;53             $i = $a[$i]; #如果數組中存在重複值,則$i必然會兩次指向同一個下標,第二次指向同一個元素時元素已置為null54             $a[$j] = null;55         }56     }57 58     $a = array(1, 2, 5, 3, 4, 5, 6, 7, 8, 9);59     echo get_dup($a) . "<br>";60     echo get_dup_xor($a) . "<br>";61     echo get_dup_bitmap($a) . "<br>";62     echo get_dup_mod($a) . "<br>";63 ?>

5
5
5
5

聯繫我們

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