【leetcode】Array——Majority Element II(229)

题目: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.

思路:

在Majority Element中,了解了Moore Voting算法。该题延续该算法,并进行改进。

如果只有一个majority,我们只需要维护一个candidate和count就行。nums[i]==candidate,count++ ;nums[i]!=candidate,count-- ; 最后candidate即为majority。

但是本题中,majority 个数大于 n/3 ,所以可能是两个,所以,维护两个candidate以及count。

(tips:用这个算法可以通过调整candidate的个数,得到nums中个数最多的数。)

通过Moore Voting得到了个数最多的两个数,仍要进行筛选,判断个数是不是大于n/3。nums[i]==candidate,count+=2; nums[i]!=candidate,count--;如果最后count>0,则是超过n/3的majority。

代码:

	public List<Integer> majorityElement(int[] nums) { 
		List<Integer> rst = new ArrayList<Integer>();
		if(nums == null || nums.length == 0) return rst;
		int count1 = 0, count2 = 0, candidate1 = 0, candidate2 = 1;
		for(int num : nums){
			if(num == candidate1) count1++;
			else if(num == candidate2) count2++;
			else if(count1 == 0){
				candidate1 = num;
				count1 = 1;
			}
			else if(count2 == 0){
				candidate2 = num;
				count2 = 1;
			}
			else{
				count1--;
				count2--;
			}
		}
		count1 = 0; count2 = 0;
		for(int num : nums){
			if(num == candidate1) count1+=2;
			else count1--;
			if(num == candidate2) count2 += 2;
			else count2--;
		}
		if(count1 > 0) rst.add(candidate1);
		if(count2 > 0) rst.add(candidate2);
		return rst;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值