LeetCode之摩尔投票法(彻底理解)

一、摩尔投票法

核心理念为 票数正负抵消 。此方法时间和空间复杂度分别为 O(N)O(N) 和 O(1)O(1)

个人理解:其实就像投票一样,
在这里插入图片描述
如图,emmmm…count的单词表数量,Candidate表候选人

  • 首先候选人1号获得票数,count+1
  • 然后候选人2号来了获得票数,抵消了1号的票数,然后候选人1号(个人认为为2号也没问题)
  • 后者在一号获得票数,然后后面2号又获得票数又抵消
  • 以此类推,最终1号获得票数最多

二、LeetCode实例

在这里插入图片描述

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

猜你喜欢

转载自blog.csdn.net/weixin_42754971/article/details/113764196