有谁做彩票网站吗,做运营必看的网站,郑州便民网,wordpress英文版变成中文版在未排序的数组中找到第 k 个最大的元素。请注意#xff0c;你需要找的是数组排序后的第 k 个最大的元素#xff0c;而不是第 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 总是有…在未排序的数组中找到第 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(vectorint nums, int begin, int end);
void swap(int first, int second);
int getIndex(vectorint nums, int start, int end);
int main() {vectorint 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(vectorint nums, int start, int end) {if (start end) {int index getIndex(nums, start, end);quickSort(nums, start, index-1);quickSort(nums, index1, end);}
}int getIndex(vectorint 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(vectorint 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, index1, nums.size()-1);}return nums[index];}int getIndex(vectorint 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(vectorint 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(vectorint 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(vectorint 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(vectorint nums, int k) {srand(time(0));return quickSelect(nums, 0, nums.size() - 1, nums.size() - k);}
}