Add time complexity in stack, queue, deque. Update heap.

This commit is contained in:
Yudong Jin
2023-01-09 02:17:40 +08:00
parent ecabb4077b
commit 6b3c87399b
8 changed files with 296 additions and 79 deletions

View File

@@ -12,28 +12,26 @@ import java.util.*;
public class heap {
public static void testPush(Queue<Integer> heap, int val) {
// 元素入堆
heap.add(val);
heap.add(val); // 元素入堆
System.out.format("\n添加元素 %d 后\n", val);
PrintUtil.printHeap(heap);
}
public static void testPoll(Queue<Integer> heap) {
// 元素出堆
int val = heap.poll();
int val = heap.poll(); // 堆顶元素出堆
System.out.format("\n出堆元素为 %d\n", val);
PrintUtil.printHeap(heap);
}
public static void main(String[] args) {
/* 初始化堆 */
// 初始化小堆
// 初始化小
Queue<Integer> minHeap = new PriorityQueue<>();
// 初始化大堆(使用 lambda 表达式修改 Comparator
// 初始化大堆(使用 lambda 表达式修改 Comparator 即可
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> { return b - a; });
System.out.println("\n以下测试样例为大顶堆");
/* 元素入堆 */
testPush(maxHeap, 1);
testPush(maxHeap, 3);
@@ -45,7 +43,7 @@ public class heap {
int peek = maxHeap.peek();
System.out.format("\n堆顶元素为 %d\n", peek);
/* 元素出堆 */
/* 堆顶元素出堆 */
testPoll(maxHeap);
testPoll(maxHeap);
@@ -56,5 +54,11 @@ public class heap {
/* 判断堆是否为空 */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\n堆是否为空 %b\n", isEmpty);
/* 输入列表并建堆 */
// 时间复杂度为 O(n) ,而非 O(nlogn)
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
System.out.println("\n输入 [1, 3, 2, 5, 4] ,建立小顶堆");
PrintUtil.printHeap(minHeap);
}
}