【剑指 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;
    }
}
相关推荐
西凉的悲伤3 小时前
SpringBoot WebClient 介绍
java·spring boot·后端·webclient
Simon523143 小时前
mybatis执行流程、关联映射、注解开发
java·开发语言·mybatis
冷雨夜中漫步3 小时前
SQLite 深度解析:在 Java/Spring 中的使用与H2、Derby对比
java·spring·sqlite
laufing3 小时前
Java 模板引擎 FreeMarker 入门教程:语法、内建函数与常用案例
java·freemarker
happymaker06263 小时前
LeetCodeHot100——128.最长连续序列
算法
wengqidaifeng3 小时前
C++从菜鸟到强手:2.类和对象(上)—— 从结构体到类的跨越
java·开发语言·c++
自律懒人3 小时前
2026年AI编程工具横评:Trae、Cursor、Claude Code、Copilot X,同一需求谁更强?
java·copilot·ai编程
余生皆假期-3 小时前
配置 CodeX 环境的 Simlink AI 工具链
笔记·单片机·嵌入式硬件·算法
qq_296553273 小时前
[特殊字符] 旋转排序数组中的高效搜索:从线性到二分查找的进阶之路
数据结构·算法·搜索引擎·分类·柔性数组
夕除3 小时前
spring boot 13
java·mysql·spring