编程语言
首页 > 编程语言> > Leetcode169. 多数元素(JAVA摩尔投票法)

Leetcode169. 多数元素(JAVA摩尔投票法)

作者:互联网

题目链接:https://leetcode-cn.com/problems/majority-element/

解题思路

这种做法应该是专门针对这题的,很巧妙。思路是这样的,我们先用ans代表备选人,x代表备选人的票数,如果等于0就要换下一个备选人(注意:下一个备选人也有可能是之前选过的备选人),由于最终答案肯定是大于一半的元素,所以最后肯定能选出答案。

代码

class Solution {
    public int majorityElement(int[] nums) {
        int ans = 0, x = 0; //ans代表备选人,x代表备选人的票数
        for(int i = 0; i < nums.length; i++) {  
            if(x == 0)  //如果当前备选人为0票,肯定就是没有备选人,直接找新备选人
                ans = nums[i];  //更新备选人
            x += ans == nums[i] ? 1 : -1;   //如果当前投的不是备选人,则x减一;是投的备选人,x加一
        }
        return ans; 
    }
} 

复杂度分析

标签:JAVA,Leetcode169,nums,int,复杂度,摩尔,ans,票数,备选
来源: https://blog.csdn.net/qq_44713772/article/details/116989360