【一天一道LeetCode】#169. Majority Element

本文介绍了LeetCode上一道寻找数组中多数元素的问题,并提供了两种解决方案。一种是通过排序找到出现次数超过一半的数;另一种是使用Boyer-Moore投票算法实现线性时间和常数空间复杂度的高效求解。

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

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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.

(二)解题

题目大意:找出数组中出现次数超过一般的数

解题思路:

最简单的就是首先对数组进行排序,然后中间的那个数就是出现次数超过一半的数。



class Solution {

public:

    int majorityElement(vector<int>& nums) {

        int len = nums.size();

        sort(nums.begin(),nums.end());//调用STL的排序函数

        return nums[len/2];

    }

};

另一种优化的算法。O(n)复杂度。

定义两个整数j和num,j记录次数,num记录一个数

当遍历到nums数组的下一个数时,如果nums[j]==num,或者j==0,此时j++,并保存num的值为nums[j],

如果j!=0且nums[j]!=num,这时候j–,由于num这个数出现次数超过一半,那么最后一个将j变成1的数就是我们要找的数。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int j = 0;//记录次数
        int ret = nums[0];//初始化为第一个数
        int size = nums.size();
        for(int i =0 ; i < size ; i++)
        {
            if(j==0||nums[i]== ret){
                ret=nums[i];
                j++;
            }
            else j--;
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值