Leetcode 169. Majority Element(找数组的主元素)

这篇博客介绍了LeetCode第169题的主要解决方案,包括使用哈希映射、分治法和摩尔投票法找出数组中出现次数超过一半的主元素。三种方法各有特点,哈希映射直接统计,分治法递归查找,摩尔投票法则通过消除不同元素实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode 169. Majority Element

题目链接: Majority Element

难度:Easy

题目大意:

找出整形数组中的主元素,即出现次数超过半数的元素。

思路1:

统计数组中各个元素的个数,出现次数最多的就是主元素。

代码

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int n:nums){
            map.put(n,map.getOrDefault(n,0)+1);
        }
        int res=0;
        for(Integer key:map.keySet()){
            if(map.get(key)>nums.length/2){
                res=key;
                break;
            }
        }
        return res;
    }
}

思路2:

分治法,分别求出左右两个区间的主元素,如果左右两个区间的主元素相同,那么该元素就是整个数组的主元素,否则比较左右区间主元素在整个数组中出现的次数,取出现次数较高的元素。

代码

class Solution {
    public int majorityElement(int[] nums) {
        return helper(nums,0,nums.length-1);
    }
    public int helper(int[] nums,int l,int r){
        //求nums[l,r]的主元素
        int n=nums.length;
        if(l==r){
            return nums[l];
        }
        int mid=l+(r-l)/2;
        int left=helper(nums,l,mid);
        int right=helper(nums,mid+1,r);
        if(left==right){
            return left;
        }
        else{
            int leftCount=countRange(nums,l,r,left);
            int rightCount=countRange(nums,l,r,right);
            return leftCount>rightCount?left:right;
        }
    }
    public int countRange(int[] nums,int l,int r,int target){
        //求nums[l,r]中等于target的元素个数
        int count=0;
        for(int i=l;i<=r;i++){
            if(nums[i]==target){
                count++;
            }
        }
        return count;
    }
}

思路3:

摩尔投票法。将不同的数同归于尽,最后剩下的一定是主元素。

代码

class Solution {
    public int majorityElement(int[] nums) {
        //摩尔投票法,将不同的数同归于尽,最后剩下的一定是主元素
        int candidate=0;
        int count=0;
        for(int n:nums){
            if(count==0){
                candidate=n;
            }
            if(n==candidate){
                count++;
            }
            else{
                count--;
            }
        }
        return candidate;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值