-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path16. Kth Largest Element in an Array
56 lines (45 loc) · 1.22 KB
/
16. 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
54
55
56
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length-k];
}
}
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq=new PriorityQueue<>(k+1);
for(int i:nums){
pq.add(i);
if(pq.size()>k){
pq.poll();
}
}
return pq.poll();
}
}
class Solution {
public int findKthLargest(int[] nums, int k) {
return quickselect(nums,0,nums.length-1,k);
}
int quickselect(int[] nums,int left,int right,int k){
int pivot=left;
for(int i=left;i<right;i++){
if(nums[i]<=nums[right]){
swap(nums,pivot++,i);
}
}
swap(nums,pivot,right);
int count=right-pivot+1;
if(count==k){
return nums[pivot];
}
else if(count>k){
return quickselect(nums,pivot+1,right,k);
}
return quickselect(nums,left,pivot-1,k-count);
}
void swap(int[] nums,int l,int r){
int temp=nums[l];
nums[l]=nums[r];
nums[r]=temp;
}
}