leetcode 169. Majority Element(大多数的元素)

在这里插入图片描述给出一个数组,找出其中过半的元素。

思路:
因为这里的假设是一定存在过半的元素。
用Moore Voting法,需要 O(n) 的时间和 O(1) 的空间。

先假设count =1 , majority是第一个元素,从左到右遍历数组,当前数字 != majority时,count–。
直到count== 0 时, 更新mojority为当前数字,count重新置为1。如果当前数字==majority,那么count++

因为题目中假设一定存在这样的元素,所以最后不需要再验证majority的个数是否>n/2

    public int majorityElement(int[] nums) {
        int n = nums.length;
        int count = 1;
        int result = nums[0];
        
        for(int i = 1; i < n; i++) {
            if(nums[i] == result) {
                count ++;
            } else {
                count --;
                if(count == 0) {
                    result = nums[i];
                    count = 1;
                }
            }
        }
        return result;
    }

如果没说一定存在,最后需要加上验证

    public int majorityElement(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        int count = 1;
        int n = nums.length;
        int major = nums[0];
        
        for(int i = 1; i < n; i++) {
            if(nums[i] == major) {
                count ++;
            } else {
                count --;
                if(count == 0) {
                    major = nums[i];
                    count = 1;
                }
            }
        }
        
        count = 0;
        for(int i = 0; i < n; i++) {
            if(nums[i] == major) {
                count ++;
            }
        }
        
        if(count > n/2) {
            return major;
        }
        
        return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值