题目
给定一个数组。其中某个数字出现次数大于 ⌊ n/2 ⌋ 次,请找出这个数字。
输入:nums = [2,2,1,1,1,2,2]
输出:2
原题链接:https://leetcode.cn/problems/majority-element/
思路
思路1
哈希法,维护一个哈希表,记录数字的次数,超过 n/2即可。
- 复杂度分析
- 时间复杂度 O(n)。遍历一次数组即可。实际不用遍历完就能找到结果。
- 空间复杂度 O(n)。实际储存数字最多为 n/2 个。
思路2
排序法。排序完后,下标为 n/2 的数字即是答案。
- 复杂度分析
- 时间复杂度 O(nlogn)。排序最快 O(nlogn)。
- 空间复杂度 O(1)。如果能在原数组中排序最好。
代码
这里只写哈希法作为示例。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> table;
int n = nums.size();
for (auto num: nums) {
if (table.count(num) == 0) {
table[num] = 0;
}
table[num]++;
if (table[num] > n/2) {
return num;
}
}
return -1;
}
};