215. 数组中的第K个最大元素 - 力扣(LeetCode)
写个快排,使数组升序,返回倒数第k个元素即可
func quickSort(nums []int, l int, r int) {
if l >= r {
return
}
x := nums[(l + r) / 2]
i := l - 1
j := r + 1
for i < j {
for {
i++
if nums[i] >= x {
break
}
}
for {
j--
if nums[j] <= x {
break
}
}
if i < j {
tmp := nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
}
quickSort(nums, l, j)
quickSort(nums, j + 1, r)
}
func findKthLargest(nums []int, k int) int {
quickSort(nums, 0, len(nums) - 1)
return nums[len(nums) - k]
}
347. 前 K 个高频元素 - 力扣(LeetCode)
统计每个元素的出现次数,按照出现次数排序即可
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> cnt;
for (const auto t : nums) {
cnt[t]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
for (const auto t : cnt) {
if (q.size() == k && q.top().first < t.second) {
q.pop();
}
if (q.size() != k) {
q.push({t.second, t.first});
}
}
vector<int> ans;
while (q.size()) {
ans.push_back(q.top().second);
q.pop();
}
return ans;
}
};