LeetCode-Majority Element II

原题链接:https://leetcode.com/problems/majority-element-ii/

题目描述:题目要求找出一个数是在一个数组中出现大于n/3次的。

思路:这道题要求用O(1)space来做,我么就不能用hashmap来。所以我们来思考Majority Element,https://leetcode.com/problems/majority-element/是怎么做的。首先我们确定一个数,设置一个计数器,如果遇到数和预先的数相等,计数器加一,不等,计数器减一。当计数器为0时,重新选择特定数。这道题也是一样,Majority 数如果是超过n/3次的话,则说明最多只有2个这样的数。我们把这两个数合在一起来计数。思路完全一样。代码如下:

public List<Integer> majorityElement(int[] nums) {
		List<Integer> res = new ArrayList<>();
		if(nums.length == 0)
			return res;
	        int a = Integer.MIN_VALUE;
		int counta = 0;
		int b = Integer.MIN_VALUE;
		int countb = 0;
		for(int i = 0;i<nums.length;i++)
		{
			if(counta == 0 )
			{
				a = nums[i];
				
			}
			else if(countb == 0)
			{
				b = nums[i];
			}
			if(nums[i] == a)
			{
				counta++;
			}
			else if(nums[i] == b)
			{
				countb++;
			}
			else
			{
				counta--;
				countb--;
			}
		}
		counta = 0;
		countb = 0;
		for(int i = 0;i<nums.length;i++)
		{
			if(nums[i] == a)
			{
				counta++;
			}
			if(nums[i] == b)
			{
				countb++;
			}
		}
		int k = nums.length/3;
		if(counta>k)
		{
			res.add(a);
		}
		if(countb>k && a!=b)
		{
			res.add(b);
		}
		return res;
    }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值