剑指offer39.数组中出现次数超过一半的数字

这个题非常简单,解法有很多种,我用的是HashMap记录每个元素出现的次数,只要次数大于数组长度的一半就返回。下面是我的代码:

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        int len = nums.length/2;
          HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
          for(int i=0;i<nums.length;i++){
              int key = nums[i];
             
              if(!map.containsKey(key)){
                  map.put(key,1);
                   if(map.get(key) > len) return key;
              }else{
                  map.put(key,map.get(key)+1);
                  if(map.get(key) > len) return key;
              }
          }
          return -1;
    }
}

题解还有一种更牛逼的解法,把数组排序,然后返回数组中间的那个数就行,因为如果这个数出现的次数大于数组长度的一半的话,排完序后数组中间那个数一定是它。

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

还有用分治法的,如果一个数是这个数组的总数,那么把这个数组分成两个子数组后,这个数至少是其中一个数组的众数,然后选出两个众数中真正的众数即可。可以采用递归的方法,不断把数组分成两个子数组,直到子数组的长度为1,合并左右两个数组,然后再不断合并,最后就可以找到整个数组的众数了

java 复制代码
class Solution {
    private int countInRange(int[] nums, int num, int lo, int hi) {
        int count = 0;
        for (int i = lo; i <= hi; i++) {
            if (nums[i] == num) {
                count++;
            }
        }
        return count;
    }

    private int majorityElementRec(int[] nums, int lo, int hi) {
        // base case; the only element in an array of size 1 is the majority
        // element.
        if (lo == hi) {
            return nums[lo];
        }

        // recurse on left and right halves of this slice.
        int mid = (hi - lo) / 2 + lo;
        int left = majorityElementRec(nums, lo, mid);
        int right = majorityElementRec(nums, mid + 1, hi);

        // if the two halves agree on the majority element, return it.
        if (left == right) {
            return left;
        }

        // otherwise, count each element and return the "winner".
        int leftCount = countInRange(nums, left, lo, hi);
        int rightCount = countInRange(nums, right, lo, hi);

        return leftCount > rightCount ? left : right;
    }

    public int majorityElement(int[] nums) {
        return majorityElementRec(nums, 0, nums.length - 1);
    }
}

还有一种Boyer-Moore 投票算法,他是先选一个候选数,先把他的次数定为0,如果下一个数和他一样次数加一,如果不一样次数减一,如果次数为0,侯选数换成下一个数,最后的侯选数就是众数。

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        Integer candidate = null;

        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }

        return candidate;
    }
}
相关推荐
一 乐27 分钟前
家政服务管理系统|基于springboot + vue家政服务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家政服务管理系统
Matrix_1130 分钟前
手机里的计算摄影:广角形变校正算法
人工智能·算法·智能手机·计算摄影
WBluuue35 分钟前
数据结构与算法:有序表(二):跳表
数据结构·c++·算法·skiplist
碳基硅坊2 小时前
Spring AI:把大模型接进 Spring 应用
java·人工智能·spring ai
黄毛火烧雪下2 小时前
Java 核心知识点总结(一)
java·开发语言
x138702859572 小时前
c语言中srtlen(指针使用计算字符长度)、传值和传址调用
c语言·开发语言·算法·visual studio
海兰2 小时前
【实用程序】电商销售分析仪表盘 — 从零搭建一个AI参与的全栈数据洞察系统
人工智能·学习·算法
技术小结-李爽2 小时前
【工具】Maven的下载、安装、使用
java·maven
极创信息2 小时前
Linux挖矿病毒深度清理实战教程,从进程隐藏、Rootkit驻留到彻底根除
java·大数据·linux·运维·安全·tomcat·健康医疗
努力成为AK大王2 小时前
并发编程的核心挑战、优化方案与核心知识点总结
java·开发语言·数据库