Leetcode No.169 Majority Element(c++实现)
1. 题目
1.1 英文题目
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.
1.2 中文题目
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
1.3输入输出
输入 | 输出 |
---|---|
nums = [3,2,3] | 3 |
nums = [2,2,1,1,1,2,2] | 2 |
1.4 约束条件
- n == nums.length
- 1 <= n <= 5 * 104
- -231 <= nums[i] <= 231 - 1
2. 分析
2.1 Moore's voting
每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
// 摩尔投票法
int candidate = nums[0]; // 候选值
for (unsigned int i = 1, count = 1; i < nums.size(); i++)
{
if (count == 0) candidate = nums[i];
count += (count == 0 || candidate == nums[i]) ? 1 : -1;
}
return candidate;
}
};
参考自:https://blog.csdn.net/huanghanqian/article/details/74188349
2.2 哈希表法
建立一个哈希表,存储元素与其出现次数;遍历给定的数组,增加其哈希表中对应的次数;如果有一个次数大于长度/2,记录答案。代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
// 哈希表法
unordered_map<int, int> hash;
int ans;
int length = nums.size();
for (int i = 0; i < length; i++)
{
hash[nums[i]]++;
if (hash[nums[i]] > length / 2)
{
ans = nums[i];
break;
}
}
return ans;
}
};
参考自:https://blog.csdn.net/weixin_44176696/article/details/104445717
2.3 位操作法
把数字都作为二进制处理,每个二进制位上的n个bit相加看是否大于n/2,大于的话这一位上是1,小于的话就是0,把32位都这么处理完即可。具体代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int i,j,count,major=0;
for(i=0;i<32;i++)
{
for(j=0,count=0;j<nums.size();j++)
{
if((nums[j]>>i&1)==1)
count++;
}
if(count>nums.size()/2)
major+=(1<<i);
}
return major;
}
};
参考自:https://www.cnblogs.com/wdfwolf3/p/5490887.html
位操作解读:https://www.cnblogs.com/zhoug2020/p/4978822.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】