215 Kth Largest Element in an Array

題目:
https://leetcode.com/problems/kth-largest-element-in-an-array/

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
int first, last;

int findKthLargest(vector<int>& nums, int k) {
srand(time(0));
return randomSelect(nums, nums.size()-k);
}

int randomSelect(vector<int>& nums, int k){
int ans = 0;
int l = 0;
int r = nums.size()-1;
while(l <= r){
partition(nums, l, r, nums[l+rand()%(r-l+1)]);
if(k < first){
r = first-1;
}
else if(k > last){
l = last+1;
}
else{
ans = nums[k];
break;
}
}
return ans;
}

void partition(vector<int>& nums, int l, int r, int x){
first = l;
last = r;
int i = l;
while(i <= last){
if(nums[i] < x){
swap(nums, first++, i++);
}
else if(nums[i] == x){
i++;
}
else{
swap(nums, last--, i);
}
}
}

void swap(vector<int>& nums, int a, int b){
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
};