-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathKthLargestElementInAnArray.java
More file actions
34 lines (31 loc) · 1.01 KB
/
KthLargestElementInAnArray.java
File metadata and controls
34 lines (31 loc) · 1.01 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
// https://leetcode.com/problems/kth-largest-element-in-an-array
// T: O(n)
// S: O(1)
public class KthLargestElementInAnArray {
public int findKthLargest(int[] nums, int k) {
int partitionIndex = nums.length - k;
for (int left = 0, right = nums.length - 1, j ; left < right ; ) {
j = partition(nums, left, right);
if (j == partitionIndex) return nums[partitionIndex];
else if (j < partitionIndex) left = j + 1;
else right = j - 1;
}
return nums[partitionIndex];
}
private int partition(int[] array, int left, int right) {
int pivot = array[right], i = left - 1;
for (int j = left ; j < right ; j++) {
if (array[j] < pivot) {
i++;
swap(array, i, j);
}
}
swap(array, i + 1, right);
return i + 1;
}
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}