Majority Element

来源:互联网 发布:原创文章是什么算法 编辑:程序博客网 时间:2024/04/26 15:52

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 objectsOutput: Majority element of aif n = 1: return a[1]k = n/2elemlsub = GetMajorityElement(a[1...k])elemrsub = GetMajorityElement(a[k+1...n]if elemlsub = elemrsub:return elemlsublcount = GetFrequency(a[1...n],elemlsub)rcount = GetFrequency(a[1...n],elemrsub)if lcount > k+1:return elemlsubelse if rcount > k+1:return elemrsubelse return NO-MAJORITY-ELEMENT

0 0
原创粉丝点击