forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkthLargestElement.java
76 lines (59 loc) · 1.65 KB
/
kthLargestElement.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class Solution {
//TC: O(nlogn) Sorting technique
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length -k];
}
// TC : nlogk MIN heap technique
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(k);
for(int el: nums){
pq.offer(el);
if(pq.size()>k){
pq.poll();
}
}
return pq.peek();
}
// Worst case O(n2)
// Best case O(n) => Quick Select techniquw
public int findKthLargest(int[] nums, int k) {
int start = 0;
int end = nums.length -1;
int index = nums.length -k;
while(start<= end){
int partionIndex = parition(nums, start, end);
if(partionIndex == index){
return nums[index];
} else if(partionIndex > index){
end = partionIndex-1;
} else if(partionIndex < index){
start = partionIndex +1;
}
}
return nums[start];
}
private int parition(int[] nums, int low, int high){
int pivot = high;
int i = low;
int j = high;
while(i<j){
while(i<j && nums[i] <=nums[pivot]){
i++;
}
while(i<j && nums[j] >=nums[pivot]){
j--;
}
swap(nums, i,j);
}
swap(nums, i, pivot);
return i;
}
private void swap(int[] nums, int i, int j){
if(i!=j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}