面试经典 150 题 - 多数元素

多数元素

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入:nums = [3,2,3]

输出:3

示例 2:

输入:nums = [2,2,1,1,1,2,2]

输出:2

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

方法一:哈希表

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }

        int max = 0;
        int res = 0;
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            if (integerIntegerEntry.getValue() > max) {
                max = integerIntegerEntry.getValue();
                res = integerIntegerEntry.getKey();
            }
        }

        return res;
    }
}

方法二:排序

如果将数组 nums 中的所有元素按照单调递增或单调递减的顺序排序,那么下标为 n/2 的元素(下标从 0 开始)一定是众数。

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}

方法三:随机化

这个思路很独特,感觉看脸。

因为超过 n/2 的数组下标被众数占据了,这样我们随机挑选一个下标对应的元素并验证,有很大的概率能找到众数。

java 复制代码
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;
            }
        }
    }
}
相关推荐
智驱力人工智能7 分钟前
极端高温下的智慧出行:危险检测与救援
人工智能·算法·安全·行为识别·智能巡航·高温预警·高温监测
旷世奇才李先生10 分钟前
奇哥面试记:SpringBoot整合RabbitMQ与高级特性,一不小心吊打面试官
spring boot·面试·java-rabbitmq
森焱森16 分钟前
60 美元玩转 Li-Fi —— 开源 OpenVLC 平台入门(附 BeagleBone Black 驱动简单解析)
c语言·单片机·算法·架构·开源
mrsk19 分钟前
🧙‍♂️ CSS中的结界术:BFC如何拯救你的布局混乱?
前端·css·面试
程序员清风1 小时前
程序员要在你能挣钱的时候拼命存钱!
后端·面试·程序员
课堂剪切板1 小时前
ch07 题解
算法·深度优先
_一条咸鱼_2 小时前
Vulkan入门教程:源码级解析
android·面试·android jetpack
前端小巷子2 小时前
深入解析CSRF攻击
前端·安全·面试
每天开心2 小时前
🧙‍♂️闭包应用场景之--防抖和节流
前端·javascript·面试
DoraBigHead2 小时前
小Dora 的 JavaScript 修炼日记 · Day 1:变量三兄弟与作用域迷宫
前端·javascript·面试