首页 > 其他 > 详细

Majority Element

时间:2015-01-17 22:05:31      阅读:292      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/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.

解题思路:

这道题的解法较多,完成后在题目的solution里可以看到总结了很多种不同的方法。

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

上面是最容易想到的排序,排序完成后,majority element不管大小,一定在最中间。

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

这是一个所谓的摩尔投票算法,可以在线性时间O(n)内解决问题。这也是一个很容易就想到的算法,不过需要总结一下才能写出。类似于不同的元素就抵消,相同的用一个数字计数的思想。基本思想是,用两个变量,candidate存前一个遍历的元素,counter用来计数。从头遍历数组,如果candidate和当前元素相同,candidate不变,counter++。如果candidate和当前元素不同,但是counter>0证明,这个candidate前面已经出现很多次了,那么counter--,抵消一次,直到counter==0。所以如果candidate和当前元素不同,而且counter==0,证明这个candidate已经被抵消了,就当前匀速取代这个candidate。如此往复,遍历整个数组。

当然,也可以用hashmap对每个元素计数,可以在线性时间内解决问题。

题目的solution里面还给到一种按位操作的方法。建立一个大小为32的数组,将原数组每个数字的每位为1的数量存入这个数组。因为majorit element的数量超过一半,那么1的数量大于一半的一定是majori element的1,0的数量大于一半的,也一定是majori elemen的0。如此还原出那个majori elemen。

Majority Element

原文:http://www.cnblogs.com/NickyYe/p/4231000.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!