在未排序的数组中找到第 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 ≤ 数组的长度。
快排参考
#include <iostream>
#include <vector>
using namespace std;void quickSort(vector<int>& nums, int begin, int end);
void swap(int& first, int& second);
int getIndex(vector<int>& nums, int start, int end);
int main() {vector<int> nums = {1,23,67,24,87,45,25,7,68,58,45,34};quickSort(nums, 0, nums.size() - 1);for (const auto& x: nums) {cout << x << " ";}cout << endl;return 0;
}void quickSort(vector<int>& nums, int start, int end) {if (start < end) {int index = getIndex(nums, start, end);quickSort(nums, start, index-1);quickSort(nums, index+1, end);}
}int getIndex(vector<int>& nums, int start, int end) {int tmp = nums[start];int low = start;int high = end;while(low < high) {while(low < high && nums[high] >= tmp) {high--;}nums[low] = nums[high];while(low < high && nums[low] <= tmp) {low++;}nums[high] = nums[low];}nums[low] = tmp;return low;
}void swap(int& first, int& second) {int tmp = first;first = second;second = tmp;
}
- 基于快排解决第K个最大元素
// 这个方法速度奇慢
class Solution {
public:int findKthLargest(vector<int>& nums, int k) {int index = getIndex(nums, 0, nums.size()-1);while(index != k-1) {index = index > k-1 ? getIndex(nums, 0, index-1) : getIndex(nums, index+1, nums.size()-1);}return nums[index];}int getIndex(vector<int>& nums, int start, int end) {int low = start;int high = end;int tmp = nums[high];while(low < high) {while(low < high && nums[low] >= tmp) {low++;}nums[high] = nums[low];while(low < high && nums[high] <= tmp) {high--;}nums[low] = nums[high];}nums[low] = tmp;return low;}void swap(int& first, int& second) {int tmp = first;first = second;second = tmp;}
}
- 优化,使用随机的index
class Solution {
public:int quickSelect(vector<int>& a, int l, int r, int index) {int q = randomPartition(a, l, r);if (q == index) {return a[q];} else {return q < index ? quickSelect(a, q + 1, r, index) : quickSelect(a, l, q - 1, index);}}inline int randomPartition(vector<int>& a, int l, int r) {int i = rand() % (r - l + 1) + l;swap(a[i], a[r]);return partition(a, l, r);}inline int partition(vector<int>& a, int l, int r) {int x = a[r], i = l - 1;for (int j = l; j < r; ++j) {if (a[j] <= x) {swap(a[++i], a[j]);}}swap(a[i + 1], a[r]);return i + 1;}int findKthLargest(vector<int>& nums, int k) {srand(time(0));return quickSelect(nums, 0, nums.size() - 1, nums.size() - k);}
}