leetcode 229. Majority Element II(主元素II)

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]

数组size=n,找出次数>n/3的所有元素
要求线性运行时间和O(1)空间

思路:
因为是线性时间,所以不能brute force, O(1) space也不能用hashtable
所以用投票法,一个元素的时候参照投票法

这里因为出现次数>n/3, 数组整体长度为n,所以最多有2个主元素,把之前的一个主元素改为两个主元素

分两步,先找candidate, 再验证candidate是否是主元素

    public List<Integer> majorityElement(int[] nums) {
        int count1 = 0;
        int count2 = 0;
        int a = 0;
        int b = 0;
        List<Integer> result = new ArrayList<>();
        int n = nums.length;
        
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == a) {
                count1 ++;
            }else if(nums[i] == b) {
                count2 ++;
            }else if (count1 == 0) {
                a = nums[i];
                count1 = 1;
            }else if (count2 == 0) {
                b = nums[i];
                count2 = 1;
            }else{
                count1 --;
                count2 --;
            }
        }
        
        count1 = 0;
        count2 = 0;
        
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == a) {
                count1 ++;
            }
            //防止出现重复元素,所以用else
            else if(nums[i] == b) {
                count2 ++;
            }
        }
        
        if(count1 > n/3) {
            result.add(a);
        }
        if(count2 > n/3) {
            result.add(b);
        }
        
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值