-
Notifications
You must be signed in to change notification settings - Fork 18
/
FindTopK.java
72 lines (62 loc) · 1.85 KB
/
FindTopK.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
69
70
71
72
package algorithm;
import java.util.Arrays;
public class FindTopK {
public static int[] getMinKNumsByHeap(int[] arr, int k) {
if (k < 1 || k > arr.length) {
return arr;
}
int[] heap = new int[k];
for (int i = 0; i < k; i++) {
heapInsert(heap, arr[i], i);
}
for (int i = k; i < arr.length; i++) {
if (arr[i] < heap[0]) {
heap[0] = arr[i];
heapify(heap, 0, k);
}
}
return heap;
}
private static void heapInsert(int[] heap, int value, int index) {
heap[index] = value;
while (index != 0) {
int parent = (index - 1) / 2;
if (heap[parent] < heap[index]) {
swap(heap, parent, index);
index = parent;
} else {
break;
}
}
}
private static void heapify(int[] heap, int index, int heapSize) {
int left = index * 2 + 1;
int right = index * 2 + 2;
int largest = index;
while (left < heapSize) {
if (heap[left] > heap[index]) {
largest = left;
}
if (right < heapSize && heap[right] > heap[largest]) {
largest = right;
}
if (largest != index) {
swap(heap, largest, index);
} else {
break;
}
index = largest;
left = index * 2 + 1;
right = index * 2 + 2;
}
}
private static void swap(int[] heap, int parent, int index) {
int tmp = heap[index];
heap[index] = heap[parent];
heap[parent] = tmp;
}
public static void main(String[] args) {
int[] a = {1, 3, 6, 4, 7, 5, 0};
System.out.println(Arrays.toString(getMinKNumsByHeap(a, 2)));
}
}