剑指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;
    }
}
相关推荐
ghie909020 分钟前
基于MATLAB的遗传算法优化支持向量机实现
算法·支持向量机·matlab
CryptoRzz25 分钟前
欧美(美股、加拿大股票、墨西哥股票)股票数据接口文档
java·服务器·开发语言·数据库·区块链
杂货铺的小掌柜1 小时前
apache poi excel 字体数量限制
java·excel·poi
大厂码农老A1 小时前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
朝新_1 小时前
【优选算法】第一弹——双指针(上)
算法
艾菜籽1 小时前
Spring MVC入门补充2
java·spring·mvc
艾莉丝努力练剑1 小时前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法
爆更小哇1 小时前
统一功能处理
java·spring boot
程序员鱼皮1 小时前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
CoovallyAIHub2 小时前
ICLR 2026 惊现 SAM 3,匿名提交,实现“概念分割”,CV领域再迎颠覆性突破?
深度学习·算法·计算机视觉