LeetCode's Moore voting method (thorough understanding)

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,
Insert picture description here
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

Insert picture description here

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;
    }

Guess you like

Origin blog.csdn.net/weixin_42754971/article/details/113764196