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

吞佛童子2022年10月10日
  • algorithm
  • 摩尔投票
小于 1 分钟

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

难度: 🌗

问题描述

img_56.png


解法

class Solution {
    public int majorityElement(int[] nums) {
        // 思路:
        // 摩尔投票
        int res = nums[0];
        int count = 1;
        int len = nums.length;
        for(int i = 1; i < len; i ++) {
            if(res == nums[i]) {
                count ++;
            } else {
                count --;
                if(count == 0) {
                    res = nums[i];
                    count = 1;
                }
            }
        }
        return res;
    }
}

输出

img_55.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou