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