leetCode 169 [PHP代碼]

來源:互聯網
上載者:User

標籤:


Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times.


You may assume that the array is non-empty and the majority element always exist in the array.


尋找多數元素
就是某一個數組中的元素的個數是N ,這個N 大於 數組個數/2 取整的值就是多數元素。

下面是PHP的代碼實現。

// array(1,2,3,2,5,69,8,2,5,2)// array(1,2,5,8,5,5,5,98,65,5,5)// array(1,2,6,8,6,6,6,98,65,6,6)echo majority(array(2,2,3,2,2,68,8,2,5,2));function majority($n) {print_r($n);echo "<br />";$elem = 0;$count = 0;// echo count($n);echo "<br />";for($i = 0; $i<count($n); $i++) {if($count == 0) {$elem = $n[$i];// print_r($elem);echo "<br />";$count = 1;}else{// print_r($n[$i]);echo "<br />";if($n[$i] == $elem) {$count++;}else{$count--;}}}if($count>0)<span style="white-space:pre"></span>return $elem;<span style="white-space:pre"></span>else<span style="white-space:pre"></span>return "Don't have majority element<br />";}

演算法描述:
將計數器置為1,並把元素1儲存下來,從元素2開始比對,逐個的比較元素。
如果被掃描的元素和儲存下來的值(元素1)相等,計數器加一,不相等,減一。
所有的元素(從元素2到結尾)比較完成計數器大於0,則返回元素一,是多數元素。否則
把元素2存入臨時變數,再比較元素3開始的整個數組。
這樣依次比較完數組。
判斷有無大數。


leetCode 169 [PHP代碼]

聯繫我們

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