169. Majority Element

题目:

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

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

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

Follow-up: Could you solve the problem in linear time and in O(1) space?

思路:

要求O(1)复杂度,这里介绍一个投票算法。用一个cur表示当前数字,用count表示当前数字"获取的票数"。遍历数组nums,遍历值为n,如果如果cur和n相同,那么count增加一;如果不同,count减少一,但是如果count小于0了,count更新为1并且cur更新为n。解析下面答复有个理解很好,引用一下,“如果碰到和当前数字(即这里的cur)不同的数,那么获取的票数(count)减一,因为不是cur的话肯定是反对票;如果相同的话获取的票数(count)加一因为当前数字(cur)会自己投给自己”。这里为什么count < 0 才更新而不是等于0就更新呢?假设[7,7,3,4],到第二个7的时候,cur=7,count=2,虽然到4的时候count为0,但是7依然是众数,因此要count小于0时,cur才会“换届”。

代码:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int cur = -1, count = 0;
        for (auto n : nums) {
            if (n == cur)
                count++;
            else {
                count--;
                if (count < 0 ){
                    count = 1;
                    cur = n;
                }
            }
        }
        return cur;
    }
};
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值