Leetcode 169. Majority Element Majority Voting algorithm (Boyer-moore Majority Vote algorithm)

Source: Internet
Author: User

Topic:

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

Assume that the array was non-empty and the majority element always exist in the array.

Solution: The use of the majority of the voting algorithm to solve the idea: to iterate through the array, encountered two different numbers to the same time to remove the two number. The two numbers that are removed may not be majority, or maybe one is majority, but because the total number of majority is greater than half (attention cannot be equal to half), so the last number that is left is majority. (because the topic said there must be majority, if not, the rest of the number is not necessarily majority, should also go through the array to count the number of occurrences).

The time complexity of this algorithm O (n), Spatial complexity O (1)

classSolution { Public:    intMajorityelement (vector<int>&nums) {        intCnt=0, ans=0;  for(Auto a:nums) {if(cnt==0) {ans=A; CNT=1; }            Else if(a==ans) {CNT++; }            Else{cnt--; }        }        returnans; }};

Extension: If you find a change greater than [N/3], the truth is exactly the same. See this question.

Leetcode 169. Majority Element Majority Voting algorithm (Boyer-moore Majority Vote algorithm)

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.