LeetCode 169. Majority Element 题解(C++)

本文介绍了一种解决LeetCode169题——寻找数组中出现次数超过一半的主元素的方法。通过遍历数组并使用抵消计数的方式,有效地找到了主元素。

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

LeetCode 169. Majority Element 题解(C++)


题目描述

  • 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.

思路

  • 这里先举个例子:假设极端情况,主元素刚好比其他所有元素的和多1个,那么一个主元素和一个其它元素互相抵消,则最终剩下的就是主元素,即使两个不同的其它元素互相抵消,则最终剩下来的还是主元素(且主元素会剩下来多个);
  • 基于上面的例子,我们可以先假设第一个元素为主元素,并使该元素的次数为t=1(即还可以用来抵消的次数),将数组从i=1开始遍历,若该元素与当前记录的主元素相等,则主元素可以与其他元素抵消的个数t自加1,若该元素与当前记录的主元素不相等,则抵消一个主元素(即t自减1),若t=0,则表明当前的主元素已经抵消完了,此时假设当前遍历到的元素为主元素,并使该元素的t设为1,继续遍历;完成遍历后得到的majority就是主元素。

代码

class Solution 
{
public:
    int majorityElement(vector<int>& nums) 
    {
        int majority = nums[0];
        int t = 1;
        for (int i = 1; i < nums.size(); ++i)
        {
            if (majority == nums[i])
            {
                ++t;
            }
            else
            {
                --t;
            }

            if (t == 0)
            {
                majority = nums[i];
                t = 1;
            }
        }
        return majority;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值