题解 | #寻找第K大#
寻找第K大
https://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
#include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param a int整型vector * @param n int整型 * @param K int整型 * @return int整型 */ int partition(vector<int>& vec, int l, int r) { int pivot = vec[l]; int i = l + 1; for (int j = l + 1; j <= r; j++) { if (vec[j] >= pivot) swap(vec[j], vec[i++]); } swap(vec[l], vec[i - 1]); return i - 1; } int findKth(vector<int>& a, int n, int K) { // write code here int res; if (n == 0) return -1; int left = 0, right = n-1; while (left <= right) { int index = partition(a, left, right); if (index + 1 == K) { return a[index]; } else if (index + 1 < K) { left = index + 1; } else { right = index - 1; } } return -1; } };