-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
54 lines (43 loc) · 1.42 KB
/
Solution.java
File metadata and controls
54 lines (43 loc) · 1.42 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null)
return 0;
int[] minHeap = new int[k + 1];
int idxOfNums = 0;
int idxOfMinHeap = 1;
int numsLen = nums.length;
while (idxOfNums < k) {
minHeap[idxOfMinHeap++] = nums[idxOfNums++];
}
buildMinHeap(minHeap, k);
while (idxOfNums < numsLen) {
if (nums[idxOfNums] > minHeap[1]) {
minHeap[1] = nums[idxOfNums];
siftDown(minHeap, 1, k);
}
idxOfNums++;
}
return minHeap[1];
}
private void buildMinHeap(int[] minHeap, int heapSize) {
int sentinel = heapSize >> 1;
for (int i = sentinel; i >= 1; i--)
siftDown(minHeap, i, heapSize);
}
private void siftDown(int[] minHeap, int idx, int heapSize) {
int sentinel = heapSize >> 1;
while (idx <= sentinel) {
int j = idx << 1;
if (j + 1 <= heapSize && minHeap[j] > minHeap[j+1])
j++;
if (minHeap[j] < minHeap[idx]) {
int tmp = minHeap[j];
minHeap[j] = minHeap[idx];
minHeap[idx] = tmp;
idx = j;
} else {
break;
}
}
}
}