3月打卡活动第13天 LeetCode第169题:多数元素(简单)

3月打卡活动第13天 LeetCode第169题:多数元素(简单)

  • 题目:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
    在这里插入图片描述
  • 解题思路:第一次尝试使用HashMap,很不熟练,但是成功了还挺开心的~~
class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer> hash = new HashMap<>();
        hash.put(nums[0],1);
        for(int i=1;i<nums.length;i++){
            if(hash.containsKey(nums[i])){
                hash.put(nums[i],hash.get(nums[i])+1);
            }else{
                hash.put(nums[i],1);
            }
        }
        for(Map.Entry<Integer,Integer> entry:hash.entrySet()){
            if(entry.getValue() > nums.length/2){
                return entry.getKey();
            }
        }
        return 0;
    }
}

在这里插入图片描述

  • 题解做法1:数组排序,这个方法也太简洁了!!
class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

  • 题解做法2:随机数的做法,在范围内随机一个数很大概率是众数。
class Solution {
    private int randRange(Random rand, int min, int max) {
        return rand.nextInt(max - min) + min;
    }

    private int countOccurences(int[] nums, int num) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == num) {
                count++;
            }
        }
        return count;
    }

    public int majorityElement(int[] nums) {
        Random rand = new Random();

        int majorityCount = nums.length/2;

        while (true) {
            int candidate = nums[randRange(rand, 0, nums.length)];
            if (countOccurences(nums, candidate) > majorityCount) {
                return candidate;
            }
        }
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

  • 题解做法3:投票算法,这个算法还是很有意思的,我想了半天。以下是我的理解。
    选一个候选众数,声明一个整型变量当作和,遍历数组,与候选众数相等+1,不等-1。和等于0时选下一位为候选众数。最终的候选众数即为真正众数。
    如果候选众数为真正众数时,最终的和一定大于0。候选众数可分为两种情况,一种是真正的众数,一种不是。当和为0时,无论它是不是真正的众数,和的情况不变。下一个候选众数的取法其实也是随机的,剩下的数越少,越容易取到众数,最终的和一定大于0。
class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        Integer candidate = null;

        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }

        return candidate;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了100 篇原创文章 · 获赞 12 · 访问量 2355

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104833485