【剑指 Offer 39】数组中超过一半的数字

题目:

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

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

示例:

输入: 1, 2, 3, 2, 2, 2, 5, 4, 2

输出: 2

思考:

  • 方法一:投机取巧

  • 将数组排序,出现次数超过一半的数字肯定在数组中间的那个位置

题解:

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

思考:

  • 方法二:哈希表辅助

  • 使用一个 map,key 存数组中的数字,val 存出现的次数

  • 当有数字出现次数超过数组长度一半时,直接返回

题解:

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();

        for(int num : nums){
            map.put(num,map.getOrDefault(num,0)+1);
            if(map.get(num)> nums.length>>1) return num;
        }
        return 0;
    }
}

思考:

  • 方法三,摩尔投票法

  • 众数和非众数投票,初始票数为 0,为 0 时假设当前数字为众数

  • 遍历数组,是众数 +1,不是众数 -1,为 0 就接着继续重新来

  • 最后得到众数

题解:

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        int vote = 0;
        int x = 0;
        for (int i = 0; i < nums.length; i++) {

            if (vote == 0) x = nums[i];

            if (x == nums[i]) vote++;
            else vote--;
        }
        return x;
    }
}
相关推荐
点云侠2 分钟前
PCL 生成三棱锥点云
c++·算法·最小二乘法
phltxy6 分钟前
Spring AI 可观测性与 Zipkin 实战
java·人工智能·spring
代码中介商10 分钟前
跳表:高效查找的链表黑科技
数据结构
兰令水14 分钟前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
临沂堇18 分钟前
刷题日志 | Leetcode Hot 100 哈希
算法·leetcode·哈希算法
.道阻且长.23 分钟前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++
蚰蜒螟25 分钟前
Java 对象的内存密语:从字段偏移量计算到 Unsafe 访问的完整链路
java·开发语言
IT 行者25 分钟前
GitHub Spec Kit 实战(六):/speckit.implement 怎么用、怎么审、怎么发现 spec 阶段的遗漏——五部曲收官
java·驱动开发·github·ai编程·claude
玉小格41 分钟前
一次关于Python的总结
算法
星辰_mya42 分钟前
CountDownLatch深度解析
java·开发语言·后端·架构