Majority element: main element

Source: Internet
Author: User

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.



The main element: An array of n elements, which is the primary element if the number of occurrences of an element is greater than N/2 (rounded down).
by definition, one of the two numbers must be the main element , set a variable cnt=0, when two numbers are the same, cnt++, not at the same time, CNT--。 With variablemajority to record the main element, each time cnt=0, assigns the current element to majority, becomes the candidate main element, thus, the final majority value must be the main element.

The code is as follows:
Class Solution {Public:int majorityelement (vector<int> &num) {    int majority;    int cnt = 0;    for (int i=0; i<num.size (); i++) {        if (cnt ==0) {            majority = Num[i];            cnt++;        } else{            Majority = = Num[i]? cnt++: CNT-;            if (cnt > Num.size ()/2) return majority;        }    }    return majority;};














Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Majority element: main element

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.