多数元素LeetCode169
投票法 O(n) time, O(1) space
一个候选人
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate, vote = 0;
for (auto num: nums) {
if (vote == 0) candidate = num;
if (candidate == num) vote ++;
else vote --;
}
return candidate;
}
};
求中位数 O(n) time, O(1) space
class Solution {
public:
int majorityElement(vector<int>& nums) {
nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
return nums[nums.size() / 2];
}
};
求众数II LeetCode229
投票法 O(n) time, O(1) space
2个候选人
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int candy1 = -2e9, candy2 = -2e9;
int vote1 = 0, vote2 = 0;
for (auto num: nums) {
if (candy1 == num) {
vote1 ++;
} else if (candy2 == num) {
vote2 ++;
} else{
if (vote1 == 0) {
candy1 = num;
vote1 ++;
} else if (vote2 == 0) {
candy2 = num;
vote2 ++;
} else {
vote1 --;
vote2 --;
}
}
}
vote1 = 0, vote2 = 0;
for (auto num: nums) {
if (num == candy1) vote1 ++;
if (num == candy2) vote2 ++;
}
vector<int> ans;
if (vote1 > nums.size() / 3) ans.push_back(candy1);
if (vote2 > nums.size() / 3) ans.push_back(candy2);
return ans;
}
};
求数组频率出现最高的k个数
计数排序思想,O(n) time, O(n) space
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> cnt; // caculate count of each num for (auto num: nums) { cnt[num] ++; } vector<int> f(nums.size() + 1); for (auto [num, c]: cnt) { f[c] ++; } int t_min = f.size() - 1; for (int i = f.size() - 1; i >= 0; i --) { k -= f[i]; t_min = i; if (k <= 0) { break; } } vector<int> ans; for (auto [num, c]: cnt) { if (c >= t_min) { ans.push_back(num); } } return ans; } };