You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution {
public:intmajorityElement(vector<int>& nums) {
unordered_map<int, int> hash;
int n = nums.size();
for (int i = 0; i < n; i++) {
hash[nums[i]]++;
}
for (auto it = hash.begin(); it != hash.end(); it++) {
if (it->second > n / 2)
return it->first;
}
return -1;
}
};
数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案
示例 1:
示例 2:
示例 3:
解法一:
用Hash Table记录每个元素的出现次数。但是空间复杂度不是O(1),代码如下:
解法二:
官方题解提供了一种方法:摩尔投票法。
基本思路是:
若candidate的出现次数大于一半,则candidate就是主要元素,否则,主要元素不存在
代码如下:
类似题目:
229. Majority Element II
The text was updated successfully, but these errors were encountered: