LeetCode kth-largest-element-in-the-array

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1:

输入: [3,2,1,5,6,4] 和 k = 2 输出: 5

示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4

说明:

你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
int findKthLargest1(vector<int>& nums, int k) {
int low = 0, high = nums.size() - 1, mid = 0;
while (low <= high) {
mid = partition(nums, low, high);
if (mid == k - 1)
return nums[mid];
else if(mid > k-1)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}

int partition(vector<int>& nums, int low, int high) {
int left = low + 1, right = high;
swap(nums[low], nums[(low+high)/2]);
int bound = nums[low];

while (left<=right) {
while(left < high && nums[left] >= bound)
++left;
while(nums[right] < bound)
--right;
if (left >= right)
break;
swap(nums[left++], nums[right--]);
}
swap(nums[low], nums[right]);
return right;
}

int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> Q; // 小根堆
for (int i = 0; i < nums.size(); ++i) { //遍历数组
if (Q.size() < k) Q.push(nums[i]); //如果堆中元素小于k,那么继续push
else if (nums[i] > Q.top()) {
Q.pop(); //如果新元素比堆中最小值大,那么弹出堆顶,压入新元素,这就是保证此堆是前K大,堆顶最小
Q.push(nums[i]);
}
}
return Q.top();
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×