-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_215v2.java
33 lines (31 loc) · 1015 Bytes
/
LC_215v2.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
public class LC_215v2 {
public int findKthLargest(int[] nums, int k) {
int n = nums.length;
for (int i = nums.length / 2; i >= 0; i--) {
buildHeap(nums, i, n);
}
for (int i = 1; i < k; i++) {
swap(nums, 0, nums.length - i);
buildHeap(nums, 0,n-i);
}
return nums[0];
}
public static void buildHeap(int[] nums, int rootIdx,int n) {
int left = rootIdx * 2 + 1;
int right = rootIdx * 2 + 2;
int maxIdx = rootIdx;
if (left < n)
if (nums[left] > nums[maxIdx]) maxIdx = left;
if (right < n)
if (nums[right] > nums[maxIdx]) maxIdx = right;
if (maxIdx != rootIdx) {
swap(nums, rootIdx, maxIdx);
buildHeap(nums, maxIdx,n);
}
}
public static void swap(int[] nums, int idx1, int idx2) {
int tmp = nums[idx1];
nums[idx1] = nums[idx2];
nums[idx2] = tmp;
}
}