Skip to content

Commit 89cc0d9

Browse files
committed
add topk example with priorityqueue
1 parent d70bf39 commit 89cc0d9

File tree

1 file changed

+28
-5
lines changed
  • zh-hans/basics_data_structure

1 file changed

+28
-5
lines changed

zh-hans/basics_data_structure/heap.md

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@
2323

2424
![Heapsort-example](../../shared-files/images/Heapsort-example.gif)
2525

26-
## 堆排实现
26+
## 堆实现
2727

28-
使用迭代实现也较为简单,注意索引值初始化和置位即可,尤其是记住最后一个索引的值 last,Java 的实现中 `pop()` 操作同时带有排序功能。
28+
使用迭代实现也较为简单,注意索引值初始化和置位即可,尤其是记住最后一个索引的值 last,Java 的实现中 `poll()` 操作同时带有排序功能。
2929

3030
### Python
3131

@@ -79,6 +79,8 @@ class MaxHeap:
7979
### Java
8080

8181
```java
82+
import java.util.*;
83+
8284
/**
8385
* Created by billryan on 29/7/2018.
8486
*/
@@ -130,10 +132,14 @@ public class MaxHeap {
130132
@Override
131133
public String toString() {
132134
StringBuilder sb = new StringBuilder();
133-
sb.append("heap array: ");
134-
for (int i : heap) {
135-
sb.append(String.format("%d, ", i));
135+
sb.append("maxHeap: [");
136+
for (int i = 0; i < last - 1; i++) {
137+
sb.append(String.format("%d, ", heap[i]));
138+
}
139+
if (last > 0) {
140+
sb.append(heap[last - 1]);
136141
}
142+
sb.append("]");
137143
return sb.toString();
138144
}
139145

@@ -150,6 +156,23 @@ public class MaxHeap {
150156
System.out.println("pop max heap value: " + maxHeap.pop());
151157
System.out.println(maxHeap);
152158
}
159+
160+
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10, Collections.reverseOrder());
161+
for (int i : array) {
162+
pq.offer(i);
163+
System.out.println(pq);
164+
}
165+
166+
// Top K problem
167+
int k = 5;
168+
for (int i = 0; i < k; i++) {
169+
Integer topk = pq.poll();
170+
if (topk != null) {
171+
System.out.println("top " + (i + 1) + ": " + topk);
172+
} else {
173+
System.out.println("poll null value!!!");
174+
}
175+
}
153176
}
154177
}
155178
```

0 commit comments

Comments
 (0)