[leetcode] 169. Majority Element

介绍一种高效查找数组中出现次数超过一半的元素的方法——多数投票算法。该算法的时间复杂度为O(n),空间复杂度为O(1)。

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.


这道题是找数组中个数超过一半的元素,题目难度为Easy。

最容易想到的办法是排序或用Hash Table统计元素个数,排序取中点元素的方法时间复杂度O(nlogn),Hash Table则需要额外的存储空间,这里介绍一下Majority Vote Algorithm,多数投票算法,时间复杂度O(n),空间复杂度O(1)。算法思路其实很简单,先上代码为敬。具体代码:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int major, count = 0;
        
        for(int num:nums) {
            if(count) {
                if(major == num) ++count;
                else --count;
            }
            else {
                major = num;
                ++count;
            }
            if(count > nums.size()/2) break;
        }
        
        return major;
    }
};
遍历数组,如果计数器为0,将当前元素暂定为Majority Element并将计数器置为1;如果计数器不为0,当前元素等于Majority Element时计数器加1,不等的话减1,这样如果存在超过一半的元素,最终记录下的Majority Element就是它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值