【LeetCode】169.Majority Element

题目:

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


解答:

这道题需要点技巧。既然已知数组中某元素E出现次数大于⌊ n/2 ⌋ 次,设想把这个数组分组,所有元素E分成一组,为G1,其余所有元素分成一组,为G2,显然G1包含的元素个数比G2多,且G1里元素与G2里元素都不相同!注意,这是重点。既然这样,那么,我每次删除一对不相同的元素,最后剩下的元素肯定是E!!(这句话看不懂的要多看几遍)


代码如下(通过OJ):

public class Solution {
    public int majorityElement(int[] num) {
		int candidate = 0,nTimes = 0;
		for(int i=0;i<num.length;i++){
			if(nTimes == 0){
				candidate = num[i];
				nTimes = 1;
			} else {
				if(candidate == num[i])
					nTimes++;
				else
					nTimes--;
			}
		}
		return candidate;
	}
}

这道题还可以推广一下,从n/2推广到n/k,即数组中必然有个MajorityElement的出现次数大于 ⌊ n/k  ⌋,如何找出这个元素呢??同样道理,分为k组,每次找到k个不相同的元素,删除之,最后剩下元素中出现次数最多的就是MajorityElement。

贴出n/3的情况代码,供大家参考:

public class Solution006 {
	/* 
	 * Given an array of size n, find the majority element. 
	 * The majority element is the element that appears more than  (n/3) times.
	 * You may assume that the array is non-empty and the majority element always exist in the array.
	 */
	public int majorityElement(int[] num) {
		int candidate1 = 0,c1Times = 0;
		int candidate2 = 0,c2Times = 0;
		for(int i=0;i<num.length;i++){
			
			if(c1Times == 0){
				candidate1 = num[i];
				c1Times = 1;
			} else if (c2Times == 0) {
				if(candidate1 == num[i])
					c1Times++;
				else {
					candidate2 = num[i];
					c2Times = 1;
				}
			} else {
				if (candidate1 == num[i])
					c1Times++;
				else if(candidate2 == num[i])
					c2Times++;
				else {
					c1Times--;
					c2Times--;
				}
			}
		}
		return c1Times > c2Times ? candidate1:candidate2;
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值