[Array]169. Majority Element

本文介绍了一种高效查找一维数组中出现次数超过一半的元素的方法。该方法采用投票机制,通过数字之间的相互抵消来找出多数元素,避免了排序带来的高时间复杂度。

摘要生成于 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.

 思路:给一个大小为n的一维数组,找到里面出现次数最多的数字。出现最多的元素的意思是在数组中出现超过一半的次数。

最暴力的算法是对数组进行排序,然后输出中间的数字。

代码如下:

int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return nums[nums.size() / 2];
    }

但是这种算法的时间复杂度会比较大。

优秀的代码是投票的方式:Every number in the vector votes for itself, the majority number gets the most votes. Different number offsets the votes.,每个数字对自己进行投票,出现次数最多的元素将会得到最多的票数,不同的数字之间会抵消投票。

具体代码如下:

int majorityElement(vector<int> &num) {
    
    int vote = num[0];
    int count = 1;
    int size = num.size();
    //vote from the second number
    for( int i = 1; i < size; i++ )
    {
        if( count == 0 ) { vote = num[i]; count++; }
        else if( vote == num[i] )    count++;
        else count--;
    }
    return vote;
    }

参考资料:https://gregable.com/2013/10/majority-vote-algorithm-find-majority.html

转载于:https://www.cnblogs.com/qinguoyi/p/7307146.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值