Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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。

posted on   NickyYe  阅读(449)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示