LeetCode刷题229. Majority Element 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]

思路解析:

你是否还记得LeetCode的第169题Majority Element,本题是169题的拓展题,⌊ n/2⌋ 变成了⌊ n/3 ⌋ ,在时间复杂度(线性时间复杂度)和空间复杂度(O(1))上提出了更高的要求。

在Majority Element中提出了一种摩尔投票算法,本题也可以用摩尔投票算法进行处理,只是稍微有点变化。

有同学不理解为什么代码中只定义了两个num和两个count,因为既然题目中已经说了“more than ⌊ n/3 ⌋ times”,那么就只能有0个,1个或者2个。如果说一个数组为[1,1,1,3,3,3,2,2,2],共有9个元素,1,2,3各有三个,这不是有3个num吗?并不是这样的,仔细一看这个数组,你会发现是找不到任何一个元素使它的个数大于9/3=3个的,它是上面所说的0个的情况。

代码如下:

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

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

James Shangguan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值