169 多数元素

一、题目

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

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

二、题解

2.1 计数法(哈希表)

遍历整个数组,对记录每个数值出现的次数(利用 HashMap,其中 key 为数值,value 为出现次数); 接着遍历 HashMap 中的每个 Entry,寻找 value 值> nums.length / 2 的 key 即可。

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int majorityElement(int[] nums) {
        // 1. 初始化一个 HashMap 来记录每个数字出现的次数
        // 键(Key)是数组里的数字,值(Value)是它出现的次数
        Map<Integer, Integer> map = new HashMap<>();

        // 2. 遍历数组,统计次数
        for (int num : nums) {
            // getOrDefault 的意思是:
            // 如果 map 里已经记录过 num 这个数字,就把它的次数取出来;
            // 如果还没有记录过,就默认次数为 0。
            // 然后把次数 +1 重新存入 map 中。
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        // 3. 计算“多数元素”需要达到的底线次数
        int limit = nums.length / 2;

        // 4. 遍历 map,找出次数超过底线的那个数字
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > limit) {
                return entry.getKey();
            }
        }

        return -1;
    }
}

时间复杂度O(n)O(n)

空间复杂度O(n)O(n)

2.2 排序法

既然数组中有出现次数 > ⌊ n/2 ⌋ 的元素,那排好序之后的数组中,相同元素 总是 相邻 的。 即存在长度 > ⌊ n/2 ⌋ 的一长串 由 相同元素 构成的 连续子数组。 举个例子: 无论是 1 1 1 2 3,0 1 1 1 2 还是 -1 0 1 1 1,数组中间的元素总是“多数元素”,毕竟它长度 > ⌊ n/2 ⌋。

import java.util.Arrays;

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length >> 1];
    }
}

时间复杂度O(nlogn)O(n \log n)

空间复杂度O(logn)O(\log n)

2.3 摩尔投票法

候选人(x)初始化为0,票数 count 初始化为 0。 当遇到与 x 相同的数,则票数 count = count + 1,否则票数 count = count - 1。 当票数 count 为 0 时,更换候选人,并将票数 count 重置为 1。 遍历完数组后,x 即为最终答案。

class Solution {
    public int majorityElement(int[] nums) {
        int x = 0, votes = 0;
        for (int num : nums){
            if (votes == 0) x = num;
            votes += num == x ? 1 : -1;
        }
        return x;
    }
}

时间复杂度O(n)O(n)

空间复杂度O(1)O(1)

评论