Leetcode 169 [PHP Code]

Source: Internet
Author: User


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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.