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.
Ideas:
Find the main element, record the main letter with Major, n record the number of occurrences of major relative to other letters
if n = = 0, set the current number as the primary number
else if the current number equals the primary number, n++
Else the current number is not equal to the primary number, n--
Since the main number appears more than half, the final major must be the main figure.
No tests, just one AC.
classSolution { Public: intMajorityelement (vector<int> &num) { intMajor; intn =0; for(inti =0; I < num.size (); i++) { if(n = =0) {Major= Num[i]; n++; } Else if(Major = =Num[i]) {N++; } Else{n--; } } returnMajor; }};
"Leetcode" Majority Element (Easy) (*^__^*)