有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
测试样例:
[1,3,5,2,2],5,3
返回:2
note:
注意手写快排的时候:
while(i < j) { while(j > i && a[j] > a[left]) j--; while(i < j && a[i] <= a[left]) i++; if(i < j) { swap(a[i],a[j]); } } while(j > i && a[j] > a[left]) j--; while(i < j && a[i] <= a[left]) i++; 这两个顺序不能反了,不然下标会错位一个
1 class Finder { 2 public: 3 int findKth(vector<int> a, int n, int K) { 4 // write code here 5 return quickfind(a,0,n - 1,K); 6 } 7 8 int quickfind(vector<int> &a,int left,int right,int K) { 9 int i = left,j = right; 10 while(i < j) { 11 while(j > i && a[j] > a[left]) j--; 12 while(i < j && a[i] <= a[left]) i++; 13 if(i < j) { 14 swap(a[i],a[j]); 15 } 16 } 17 swap(a[left],a[i]); 18 int dis = right - i + 1; 19 if(dis == K){ 20 return a[i]; 21 } 22 else if(K < dis) { 23 return quickfind(a,i + 1,right,K); 24 } 25 else{ 26 return quickfind(a,left,i - 1 ,K - dis); 27 } 28 } 29 };
--------------------------------------------------
leetcode:
215. Kth Largest Element in an Array
QuestionEditorial Solution
- Total Accepted: 67793
- Total Submissions: 195182
- Difficulty: Medium
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array‘s length.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Show Similar Problems
1 class Solution { 2 public: 3 int findKthLargest(vector<int>& nums, int k) { 4 return quickfind(nums,0,nums.size() - 1,k); 5 } 6 7 int quickfind(vector<int> &a,int left,int right,int K) { 8 int i = left,j = right; 9 while(i < j) { 10 while(j > i && a[j] > a[left]) j--; 11 while(i < j && a[i] <= a[left]) i++; 12 if(i < j) { 13 swap(a[i],a[j]); 14 } 15 } 16 swap(a[left],a[i]); 17 int dis = right - i + 1; 18 if(dis == K){ 19 return a[i]; 20 } 21 else if(K < dis) { 22 return quickfind(a,i + 1,right,K); 23 } 24 else{ 25 return quickfind(a,left,i - 1 ,K - dis); 26 } 27 } 28 };
时间: 2024-10-16 07:19:31