-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth-largest-element-in-an-array.java
65 lines (50 loc) · 1.11 KB
/
kth-largest-element-in-an-array.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
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> queue = new PriorityQueue<>();
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
if (queue.size() > k) {
queue.poll();
}
}
return queue.peek();
}
}
class Solution {
public int findKthLargest(int[] nums, int k) {
k = nums.length - k;
int start = 0;
int end = nums.length - 1;
while (start < end) {
int pivot = nums[start];
int j = start;
swap(start, end, nums);
for (int i = start; i < end; i++) {
if (nums[i] <= pivot) {
swap(i, j, nums);
j++;
}
}
swap(j, end, nums);
if (j == k) {
return pivot;
} else if (j < k) {
start = j + 1;
} else {
end = j - 1;
}
}
return nums[start];
}
public void swap(int i, int j, int[] nums) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}