-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path215-数组中第k大个元素.cpp
More file actions
36 lines (36 loc) · 1.04 KB
/
215-数组中第k大个元素.cpp
File metadata and controls
36 lines (36 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return findKthLargestElement(k,nums,0,nums.size()-1);
}
int findKthLargestElement(int k,vector<int>& nums,int start,int end)
{
if(start==end)
return nums[start];
int index = partition(nums,start,end);
if(end-index+1==k)
return nums[index];
else if(end-index+1>k)
return findKthLargestElement(k,nums,index+1,end);
else
return findKthLargestElement(k-(end-index+1),nums,start,index-1);
}
int partition(vector<int>&nums,int start,int end)
{
int x = (start+end)/2;
swap(nums[start],nums[x]);
int i = start+1;
int j = i;
while(i<=end&&j<=end)
{
if(nums[j]<nums[start])
{
swap(nums[i],nums[j]);
i++;
}
j++;
}
swap(nums[start],nums[i-1]);
return i-1;
}
};