LeetCode 229. Majority Element II(摩尔投票法)

229. Majority Element II

Medium

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]
Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

题意

给定一个长度为n的数组,求出现次数大于n/3的元素(一个或两个)

思路

LeetCode 169. Majority Element的姊妹题,也是摩尔投票法的变式,实现O(n)时间复杂度和O(1)空间复杂度的算法。
使用两套变量(cand1, cnt1),(cand2, cnt2)分别存储第一个可能的元素和第二个可能的元素及其出现次数。cand1, cand2(如果存在的话),出现的次数会大于其余元素出现次数之和,因此摩尔投票法仍然适用。
和寻找出现次数大于n/2的元素不同的一点是,在本题中,符合要求的元素有可能有一个([1,1,1,1,2] -> 1),有可能有两个([1,1,2,2,3] -> 1,2),通过一次循环求出cand1和cand2之后,还要通过一次循环求出cand1和cand2的出现次数验证是否大于n/3.

代码

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        int cand1 = 0, cand2 = 0, cnt1 = 0, cnt2 = 0;
        for (int num: nums) {
            if (cnt1 == 0 && num != cand2) {
                cand1 = num; 
            }
            if (cnt2 == 0 && num != cand1) {
                cand2 = num;
            }
            if (cand1 == num) {
                ++cnt1;
            } else if (cand2 == num) {
                ++cnt2;
            } else {
                if (cnt1 > 0) {
                    --cnt1;
                }
                if (cnt2 > 0) {
                    --cnt2;
                }
            }
        }
        // System.out.println(cand1 + " " + cand2);
        cnt1 = 0;
        cnt2 = 0;
        for (int num: nums) {
            if (cand1 == num) {
                ++cnt1;
            } else if (cand2 == num) {
                ++cnt2;
            }
        }
        ArrayList<Integer> arr = new ArrayList<Integer>();
        if (cnt1 > nums.length/3) {
            arr.add(cand1);
        }
        if (cnt2 > nums.length/3) {
            arr.add(cand2);
        }
        return arr;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值