-
Notifications
You must be signed in to change notification settings - Fork 118
/
KthLargestElement.java
68 lines (57 loc) · 1.88 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
package Algorithms;
import java.util.ArrayList;
import java.util.Collections;
class KthLargestElement {
//param k : description of k
//param numbers : array of numbers
//return: description of return
public static void main(String[] strs) {
KthLargestElement Kth = new KthLargestElement();
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(9);
numbers.add(3);
numbers.add(2);
numbers.add(4);
numbers.add(8);
System.out.println(Kth.kthLargestElement(3, numbers));
}
public int kthLargestElement(int k, ArrayList<Integer> numbers) {
// write your code here
// write your code here
Integer[] num = new Integer[numbers.size()];
numbers.toArray(num);
//Integer[] num = numbers.toArray(new Integer[0]);
return findKthNumberHelp(num, num.length + 1 - k, 0, num.length - 1);
}
public int findKthNumberHelp(Integer[] num, int k, int start, int end) {
int left = start;
int right = end;
int pivot = left;
while (left <= right) {
while (left <= right && num[left] <= num[pivot]) {
left++;
}
while (left <= right && num[right] >= num[pivot]) {
right--;
}
if (left < right) {
swap(num, left, right);
}
}
swap(num, pivot, right);
if (right + 1 == k) {
return num[right];
}
if (right + 1 > k) {
// find in the left side.
return findKthNumberHelp(num, k, start, right - 1);
} else {
return findKthNumberHelp(num, k, right + 1, end);
}
}
private void swap(Integer[] num, int one, int two) {
int tmp = num[one];
num[one] = num[two];
num[two] = tmp;
}
};