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.

题意:找数组里数目超过一半的那个元素。

思路:排序,然后中间那个元素

public int majorityElement(int[] num) {
        Arrays.sort(num);
        return num[num.length/2];
}

看了solution,好多种方法 = = 

又做了里面那种叫做Moore voting algorithm的,可以达到O(n)

We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:

  1. If the counter is 0, we set the current candidate to x and the counter to 1.
  2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O( n ).

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

网上搜了一下,有大神说 “ 每找出两个不同的element,则成对删除。最终剩下的一定就是所求的。”

这么一说马上豁然开朗。

solution还介绍了个分治方式的,谷歌搜了下,看到一份解题报告,只有伪码,感觉伪码好像是不对的,还是跟着实现,果然没过 = = 

坐等大神代码

procedure GetMajorityElement(a[1...n])
Input: Array a of objects
Output: Majority element of a
if n = 1: return a[1]
k = n/2

elemlsub = GetMajorityElement(a[1...k])
elemrsub = GetMajorityElement(a[k+1...n]
if elemlsub = elemrsub:
return elemlsub
lcount = GetFrequency(a[1...n],elemlsub)
rcount = GetFrequency(a[1...n],elemrsub)
if lcount > k+1:
return elemlsub
else if rcount > k+1:
return elemrsub
else return NO-MAJORITY-ELEMENT

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值