標籤:
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代碼]