题意
题解
方法一:小顶堆
C++提供的priority_queue
默认是大顶堆
//降序队列,大顶堆
priority_queue<int> q;
priority_queue <int,vector<int>,less<int> >q;
//升序队列,小顶堆
priority_queue <int,vector<int>,greater<int> > q;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> heap;
for (int i = 0; i < k; i++) {
heap.push(nums[i]);
}
for (int i = k; i < nums.size(); i++) {
if (heap.top() < nums[i]) {
heap.pop();
heap.push(nums[i]);
}
}
return heap.top();
}
};
方法二:快速排序
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
srand((unsigned)time(NULL));
return nums[findKth(nums, 0, nums.size() - 1, k)];
}
int findKth(vector<int>& nums, int left, int right, int K) {
int pos = randomized_partition(nums, left, right);
if (pos == (right - K + 1)) {
return pos;
} else if (pos < (right - K + 1)) {
return findKth(nums, pos + 1, right, K);
} else {
return findKth(nums, left, pos - 1, K - (right - pos + 1));
}
}
int randomized_partition(vector<int>& nums, int l, int r) {
int i = rand() % (r - l + 1) + l;
swap(nums[l], nums[i]);
return partition(nums, l, r);
}
int partition(vector<int>& nums, int left, int right) {
int num = nums[left];
while (left < right) {
while (left < right && nums[right] >= num) right--;
nums[left] = nums[right];
while (left < right && nums[left] <= num) left++;
nums[right] = nums[left];
}
nums[left] = num;
return left;
}
};