剑指offer 39. 数组中出现次数超过一半的数字

剑指offer 39. 数组中出现次数超过一半的数字

题目描述

在这里插入图片描述

解题思路

摩尔投票

在这里插入图片描述

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        int mostNum = 0, votes = 0;

        for (int num : nums) {
    
    
            //票数为0,则选取当前的新元素为众数
            if (votes == 0) {
    
    
                mostNum = num;
                votes++;
            } else {
    
    
                //如果当前元素等于众数,则票数加1,否则减1
                votes += (num == mostNum) ? 1 : -1;
            }
        }
        return mostNum;
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115254580
今日推荐