leetcode 169 Majority Element

本文介绍了一种寻找数组中多数元素的有效算法。多数元素是指在数组中出现次数超过一半的元素。文章提供了一个O(n)时间复杂度的解决方案,并附带了C++代码实现。

摘要生成于 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.
本题非常简单,写出来主要是方便准备面试的同学,这道题在面试题中出现的概率十分高,所以这里说明一下思路。

O(nlogn)的算法很容易实现,排序一下基本就OK,但是这种思路并不满足面试官的要求,通常会要求O(n)的思路。
观察数组就会发现一个很有趣的现象,达到majority要求的元素,总会出现位置相邻的情况,我们利用这个特点,对数组进行遍历,即可得到最后的结果。
代码实现如下(C++11):
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 1;
if(nums.size()==0)
return 0;
int max = nums[0];
for(int i = 1;i<nums.size();i++) {
if(nums[i]==max) {
count++;
}else {
count--;
}
if(count<=0) {
max = nums[i];
count = 1;
}
}
if(count>0) {
count = 0;
for(auto&val:nums) {
if(val == max)
count++;
}
}
if(count>nums.size()/2)
return max;
return 0;
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值