Topic:
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.
Solution: The use of the majority of the voting algorithm to solve the idea: to iterate through the array, encountered two different numbers to the same time to remove the two number. The two numbers that are removed may not be majority, or maybe one is majority, but because the total number of majority is greater than half (attention cannot be equal to half), so the last number that is left is majority. (because the topic said there must be majority, if not, the rest of the number is not necessarily majority, should also go through the array to count the number of occurrences).
The time complexity of this algorithm O (n), Spatial complexity O (1)
classSolution { Public: intMajorityelement (vector<int>&nums) { intCnt=0, ans=0; for(Auto a:nums) {if(cnt==0) {ans=A; CNT=1; } Else if(a==ans) {CNT++; } Else{cnt--; } } returnans; }};
Extension: If you find a change greater than [N/3], the truth is exactly the same. See this question.
Leetcode 169. Majority Element Majority Voting algorithm (Boyer-moore Majority Vote algorithm)