229. Majority Element II (E)

本文介绍了一种线性时间和常数空间复杂度的算法,用于在数组中找出所有出现次数超过n/3的元素。通过摩尔投票法Boyer-MooreMajorityVote,我们能够有效地筛选出可能的候选元素,并进一步验证它们是否满足条件。

Majority Element II (E)

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/3 ⌋的元素。

思路

限制时间为O(N)、空间为O(1),因此不能用Hash或者排序。使用 169. Majority Element (E) 中提到的摩尔投票法 Boyer-Moore Majority Vote。求所有出现次数大于⌊ n/3 ⌋的元素,用反证法很容易证明这种元素最多只有两个,所以可以先用摩尔投票法获得两个候选元素,再重新遍历数组统计候选元素出现的次数,将满足条件的加入到结果集中。


代码实现

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> ans = new ArrayList<>();
        int a = 0, b = 0;
        int countA = 0, countB = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == a) {
                countA++;
            } else if (nums[i] == b) {
                countB++;
            } else if (countA == 0) {
                a = nums[i];
                countA = 1;
            } else if (countB == 0) {
                b = nums[i];
                countB = 1;
            } else {
                countA--;
                countB--;
            }
        }
        countA = 0;
        countB = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == a) {
                countA++;
            } else if (nums[i] == b) {
                countB++;
            }
        }
        if (countA > nums.length / 3) {
            ans.add(a);
        }
        if (countB > nums.length / 3) {
            ans.add(b);
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值