【剑指 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;
    }
}
相关推荐
Brookty6 分钟前
Java博客项目实战|工程环境与构建:工程目录、PowerShell命令调用与JDK/IDEA/Maven工作机制
java·项目实战
octopus_c19 分钟前
STL 之 string:auto 与范围 for、常用接口、模拟实现与深浅拷贝
开发语言·c++·算法
养军博客30 分钟前
Spring Boot 3.x + Spring Security 6.x 整合 JWT 实战:jjwt 与 java-jwt 两种工具库详解
java·spring boot·springsecurity
TeamDev39 分钟前
使用 JxBrowser 在桌面应用中集成 Spring
java·前端·后端·spring·混合应用·jxbrowser·浏览器控件
J.YA1 小时前
String字符串[面试题]
java·开发语言
金銀銅鐵10 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
文丑颜不良啊12 小时前
LeetCode1941~1960题目解析
java·leetcode
txxzjmzlh12 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj52014 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河6614 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql