1. Moore voting method
The core idea is to offset the number of votes. The time and space complexity of this method are O(N)O(N) and O(1)O(1) respectively
Personal understanding: In fact, it is like voting,
as shown in the figure, the number of word lists in emmmm...count, and Candidate list candidates
- First candidate 1 gets the number of votes, count+1
- Then the candidate No. 2 came to get the number of votes, which offset the number of votes of No. 1, and then the candidate No. 1 (personally thinks No. 2 is no problem)
- The latter gets the number of votes on the first number, and then gets the number of votes and offsets it
- By analogy, in the end, No. 1 got the most votes
Two, LeetCode instance
class Solution {
public int majorityElement(int[] nums) {
int count = 1;
int candidate = nums[0];
for (int i = 1; i < nums.length; i++) {
if (candidate == nums[i]){
count++;
}else {
count--;
if (count == 0) {
//若count为0,更换候选人
candidate = nums[i];
count++;
}
}
}
return candidate;
}