[Lintcode] Majority number (main element in time complexity O (n))

Source: Internet
Author: User
Tags lintcode

The main element of a data series is the element in the sequence that occurs more than half the length of the sequence.

Method 1 (Expected time complexity is O (n)):

Because the main element occurs more than half the length of the sequence, the main element must be the median. Recursive partitioning can be used to find the median, and the expected time complexity is O (n).

Act 2:

Obviously, if a sequence has the main element, then we remove the different two numbers in the sequence, and the main element of the remaining sequence is the same as the primary element of the original sequence.

Specific algorithm operation: Record two quantities, current element x, Count cnt. Initialize CNT to 0, then traverse the sequence, if CNT is 0, the x is set to the current element and the CNT to 1, otherwise, if the current element and X are the same, then cnt++, if the current element and X are different, then cnt--; after the traversal, X is the primary element.

The code is implemented as follows:

1 classSolution {2  Public:3     /**4 * @param nums:a list of integers5 * @return: The majority number6      */7     intMajoritynumber (vector<int>v) {8         //Write your code here9         intX, cnt =0;Ten          for(intI=0; I!=v.size (); ++i) One         { A             if(cnt==0) x = V[i], cnt =1; -             Elsev[i]==x?++cnt:--CNT; -         } the         returnx; -     } -};

[Lintcode] Majority number (main element in time complexity O (n))

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.