码迷,mamicode.com
首页 > 其他好文 > 详细

169. Majority Element - LeetCode

时间:2018-06-21 23:43:17      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:return   finally   jpg   --   when   com   number   int   一半   

Question

169. Majority Element

技术分享图片

Solution

思路:构造一个map存储每个数字出现的次数,然后遍历map返回出现次数大于数组一半的数字.

还有一种思路是:对这个数组排序,次数超过n/2的元素必然在中间.

Java实现:

public int majorityElement(int[] nums) {
    Map<Integer, Integer> countMap = new HashMap<>();
    for (int num : nums) {
        Integer count = countMap.get(num);
        if (count == null) {
            count = 0;
        }
        countMap.put(num, count+1);
    }
    for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
        if (entry.getValue() > nums.length/2) {
            return entry.getKey();
        }
    }
    return 0;
}

在讨论区看到一个创新的解法:

public int majorityElement(int[] num) {

    int major=num[0], count = 1;
    for(int i=1; i<num.length;i++){
        if(count==0){
            count++;
            major=num[i];
        }else if(major==num[i]){
            count++;
        }else count--;

    }
    return major;
}

这是讨论中对该解法的一个说明:

1)According to problem Major element appears more than ? n/2 ? times

2)Count is taken as 1 because 1 is the least possible count for any number ,

3)Major element is updated only when count is 0 which means --Array has got as many non major elements as major element

4) Check this case 1,1,3,3,5,3,3 ---Majority element is 1 initially count becomes 0 at after 2nd 3 and 5 is made as majority element with count=1 and finally 3 is made as major element.

Major Element是出现次数大于n/2的一个数,遍历这个数组时,只有Major Element才能保证count>0.

169. Majority Element - LeetCode

标签:return   finally   jpg   --   when   com   number   int   一半   

原文地址:https://www.cnblogs.com/okokabcd/p/9211227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!