主元素(出现次数超过n/3)Majority Element II

本文介绍两种高效算法来找出数组中出现频率超过n/3的元素,第一种方法通过对数组进行排序来实现,第二种方法采用推举法,利用数组特性减少计算复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

解决:

① 将数组排序后计算出现次数。

class Solution { //5ms
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        Arrays.sort(nums);
        int count = 1;
        int len = nums.length;
        for (int i = 1;i < nums.length;i ++){
            if (nums[i] == nums[i - 1]){
                count ++;
            }else {
                if (count > len / 3){
                    res.add(nums[i - 1]);
                }
                count = 1;
            }
        }
        if (count > len / 3){
            res.add(nums[len - 1]);
        }
        return res;
    }
}

② 推举法,规律:任意一个数组出现次数大于n/3的众数最多有两个

class Solution { //3ms
    public List<Integer> majorityElement(int[] nums) {
        int num1 = 0;
        int num2 = 0;
        int count1 = 0;
        int count2 = 0;
        for (int num : nums){
            if (num == num1){
                count1 ++;
            }else if (num == num2){
                count2 ++;
            }else if (count1 == 0){
                num1 = num;
                count1 ++;
            }else if (count2 == 0){
                num2 = num;
                count2 ++;
            }else {
                count1 --;
                count2 --;
            }
        }
        count1 = 0;
        count2 = 0;
        for (int num : nums){
            if (num == num1){
                count1 ++;
            }else if (num == num2){
                count2 ++;
            }
        }
        List<Integer> res = new ArrayList<>();
        if (count1 > nums.length / 3) res.add(num1);
        if (count2 > nums.length / 3) res.add(num2);
        return res;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1591542

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值