题目分析:[[EVD]] - 剑指 Offer 39. 数组中出现次数超过一半的数字
https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
简单描述:
- 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
- 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
限制🚫
- 1 <= 数组长度 <= 50000
示例:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
解题思路:
思路:
- #哈希表 打表判断
- #排序 排序后,数组中点元素一定为该题所要找的众数
- #摩尔投票法 核心理念为 票数正负抵消,占半数以上的数字必然留到最后
效率:
- 时间复杂度
- 哈希表 空间复杂度
- 摩尔投票法 空间复杂度
- 哈希表 空间复杂度
代码:
- 1.哈希表
class Solution {
public:
unordered_map <int,int> map; //默认初始化为0
int majorityElement(vector<int>& nums) {
for(auto num:nums){
map[num]++;
if(map[num]>nums.size()/2)
return num;
}
return 0;
}
};
- 2.摩尔投票法
class Solution
{
public:
/*摩尔投票法*/
int majorityElement(vector<int> &nums)
{
int x = 0, votes = 0, cnt = 0;
for (int num : nums)
{
if (votes == 0)
x = num;
votes += num == x ? 1 : -1;
}
// 验证 x 是否为众数,该题确保给定的数组总是存在多数元素
for (int num : nums)
if (num == x)
cnt++;
return cnt > nums.size() / 2 ? x : 0; // 当无众数时返回 0
}
};