剑指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;
    }
}
相关推荐
ChinaRainbowSea13 小时前
9. LangChain4j + 整合 Spring Boot
java·人工智能·spring boot·后端·spring·langchain·ai编程
ゞ 正在缓冲99%…13 小时前
leetcode35.搜索插入位置
java·算法·leetcode·二分查找
武昌库里写JAVA13 小时前
Mac下Python3安装
java·vue.js·spring boot·sql·学习
lifallen13 小时前
字节跳动Redis变种Abase:无主多写架构如何解决高可用难题
数据结构·redis·分布式·算法·缓存
程序员清风13 小时前
滴滴三面:ZGC垃圾收集器了解吗?
java·后端·面试
feifeigo12313 小时前
星座SAR动目标检测(GMTI)
人工智能·算法·目标跟踪
WWZZ202513 小时前
视觉SLAM第10讲:后端2(滑动窗口与位子图优化)
c++·人工智能·后端·算法·ubuntu·机器人·自动驾驶
扯淡的闲人14 小时前
多语言编码Agent解决方案(4)-Eclipse插件实现
java·ide·eclipse
YuTaoShao14 小时前
【LeetCode 每日一题】36. 有效的数独
linux·算法·leetcode
IT古董14 小时前
【漫话机器学习系列】003.Agglomerative聚类
人工智能·算法·机器学习