Given an array of size n, find the majority element. The majority element is the element, which appears more than? N/2? Times.
Assume that the array was non-empty and the majority element always exist in the array.
Find most elements
That is, the number of elements in an array is n, and the value of this n is greater than the number of arrays/2 is the majority element.
The following is the code implementation of 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/>";}
Algorithm Description:
Set the counter to 1 and save the element 1, starting with element 2, comparing elements one by one.
If the scanned element is equal to the saved value (element 1), the counter is incremented by one, not equal, minus one.
All elements (from element 2 to end) Compare the completion counter to more than 0, then return element one, which is the majority element. Otherwise
The element 2 is stored in a temporary variable, and then the entire array starting with element 3 is compared.
The array is then compared in turn.
Judge if there is no large number.
Leetcode 169 [PHP Code]