zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    P1012拼数
    P1622释放囚犯
    P1064 金明的预算方案
    P1754球迷购票问题
    卡塔兰数
    P1474货币系统
    P2562kitty猫基因
    P3984高兴的津津
    5-servlet简介
    java通过百度AI开发平台提取身份证图片中的文字信息
  • 原文地址:https://www.cnblogs.com/okokabcd/p/9211227.html
Copyright © 2011-2022 走看看