摩尔投票法

练习题目

  1. 多数元素
  2. 求众数 II

以229题为例,给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素,尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

我们可以很容易想到用map来解决该问题,但是不满足其复杂度要求,改用摩尔投票法来解决。
摩尔投票法分为两步,第一步抵消阶段,选定候选人后,如果后续的人不一致则减少其投票,当其票数为0后,更换候选人;第二部得到所有的候选人后,遍历统计其出现次数,看看是否满足要求。

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums.length==0) {
            return res;
        }

        int candidate1 = nums[0];
        int candidate2 = nums[0];
        int count1 = 0;
        int count2 = 0;

        for (int num:nums) {
            if (candidate1 == num) {
                count1++;
                continue;
            }

            if (candidate2 == num) {
                count2++;
                continue;
            }

            if (count1 == 0) {
                count1++;
                candidate1=num;
                continue;
            }

            if (count2 == 0) {
                count2++;
                candidate2=num;
                continue;
            }

            count1--;
            count2--;
        }

        count1=0;
        count2=0;
        for (int num:nums) {
            if (num == candidate1) {
                count1++;
            } else if (num == candidate2) {
                count2++;
            }
        }

        if (count1>nums.length/3) {
            res.add(candidate1);
        }

        if (count2>nums.length/3) {
            res.add(candidate2);
        }

        return res;
    }
}
posted @ 2021-01-09 18:44  hunter-w  阅读(177)  评论(0编辑  收藏  举报