0313-2020-LEETCODE-169-数组中的多数元素(Hash-排序-摩尔投票)

排序法和摩尔投票法都是不错的方法。
部分代码参考来源:https://leetcode-cn.com/problems/majority-element/solution/3chong-fang-fa-by-gfu-2/

public int majorityElement1(int[] nums) {
        int len = nums.length;
        int midLen = len >> 2;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            if (map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i]) + 1);
            } else {
                map.put(nums[i],1);
            }
        }
        for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
            if (entry.getValue() > midLen){
                return entry.getKey();
            }
        }
        return 0;
    }
    //排序法
    public int majorityElement2(int[] nums){
        Arrays.sort(nums);
        return nums[nums.length >> 1];
    }
    //摩尔投票法
    public int majorityElement3(int[] nums){
        int cand_num = nums[0],count = 1;
        for (int i = 1; i < nums.length; ++i) {
            if (nums[i] == cand_num){
                ++count;
            } else {
                if (--count == 0){
                    cand_num = nums[i];
                    count = 1;
                }
            }
        }
        return cand_num;
    }
发布了98 篇原创文章 · 获赞 0 · 访问量 2201

猜你喜欢

转载自blog.csdn.net/weixin_43221993/article/details/104836606