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.
Puzzle: Set Two variables, one is current, initialize to A[0], and the other is count, which records the number of times this element has been present so far. Then iterate a, if the current element is equal, count plus 1; otherwise, see if Count is 0, if Count is already 0, the current element is directly assigned to it, and if Count is not 0, subtract count by one.
The basic idea is to find an unequal element pair, if there are two unequal elements, they cancel the two, then the last not offset the element, that is, the number of occurrences more than ⌊n/2⌋.
Java Version Code:
1 Public classSolution {2 Public intMajorityelement (int[] num) {3 intCurrent = Num[0];4 intCount = 0;5 for(inti = 1;i < num.length;i++){6 if(Current = =Num[i])7count++;8 Else{9 if(Count >0){Tencount--; One}Else { ACurrent =Num[i]; - } - } the } - returnCurrent ; - } -}
"Leetcode Brush Question notes" Majority Element