leetcode 169. Majority Element -思路难

本文详细解析了寻找主数的算法,主数是指数组中出现次数超过一半的元素。通过设定第一个元素为主数并计数,遍历数组,当遇到相同元素时增加计数,不同则减少,计数为0时更新主数。该算法巧妙地利用了主数出现次数的特性,实现了高效查找。

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

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3
Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

题意:寻找主数,主数就是一个数组中个数大于n/2的数,题目默认数组一定存在主数

思路:既然主数个数大于n/2,则不管以怎样的顺序排列,主数的个数都可以抵消掉其他数。所以先设第一个数是主数,用count记录当前主数的相差数,如果后面那个数与主数相等,count+1,不等count-1。当count<=0时,更换当前值为主数

class Solution {
    public int majorityElement(int[] nums) {
        int len = nums.length;
        int count = 1;//默认第一个数为主数,相差数为1
        int main = nums[0];
        for(int i=1;i<len;i++){//从数组第二位开始循环判断
            if(nums[i] == main) {//如果当前数等于主数
                count++;
            }else{//如果当前数不等于主数
                if(count>0){//并且相差数>0,即主数的次数没有被抵消完
                    count--;
                }else{//不等并且相差数<=0,主数次数已经被抵消完
                    main = nums[i];//重新设置主数
                    count = 1;//主数相差数为1                   
                }
            }
        }
        return main;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值