• 169. Majority Element


    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

    1. 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.

  • 相关阅读:
    电路分析
    python-字典
    python-异常
    python-抽象类和抽象方法
    pyqt5-QAbstractScrollArea滚动条
    python-类的继承
    python-语言播报
    pyqt5-QFrame边框样式
    流媒体技术学习笔记之(三)Nginx-Rtmp-Module统计某频道在线观看流的客户数
    让你的 Nginx 的 RTMP 直播具有统计某频道在线观看用户数量的功能
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9211227.html
Copyright © 2020-2023  润新知