题解 | 寻找第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 partion(vector<int>& a, int low, int high) { // int temp = a[low]; // while (low < high) { // while (low < high && temp >= a[high]) // high--; // if (low == high)break; // else a[low] = a[high]; // while (low < high && temp <= a[low]) // low++; // if (low == high)break; // else a[high] = a[low]; // } // a[low] = temp; // return low; // } // int QuickSort(vector<int>& a, int low, int high, int K){ // int p = partion(a, low, high); // if(K == p - low + 1) // return a[p]; // else if(K > p - low + 1) // //需要减去前面的数 // return QuickSort(a, p + 1, high, K - (p - low + 1)); // else // return QuickSort(a, low, p-1, K); // } int findKth(vector<int>& a, int n, int K) { // write code here //目的是求第K大的数,快速排序后倒序; // return QuickSort(a, 0, n - 1, K); sort(a.begin(), a.end()); return a[n-K]; } };