From bde70cebf95ab24fec2ee38ec1a0b8554d5b8146 Mon Sep 17 00:00:00 2001 From: Leon Xu Date: Mon, 21 Mar 2022 15:58:49 -0700 Subject: [PATCH] doc: add priorityqueue (heap) section to data structure post --- source/_posts/数据结构.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/source/_posts/数据结构.md b/source/_posts/数据结构.md index 155eb51..5872bd9 100644 --- a/source/_posts/数据结构.md +++ b/source/_posts/数据结构.md @@ -157,4 +157,19 @@ deque.offerLast(2); // 1 -> 2 deque.offerFirst(0); // 0 -> 1 -> 2 deque.peekFirst(); // return 0; deque.pollFirst(); // return 0; -deque.pollLast(); //return 2; \ No newline at end of file +deque.pollLast(); //return 2; + +## PriorityQueue(Heap) 堆(最大堆,最小堆) +堆分为两种:最大堆和最小堆,两者的区别在于节点的排序方式。 +![堆](images/PriorityQueue(Heap).png) +在最大堆中,父节点的值比每一个子节点的值都要打。在最小堆中,父节点的值比每一个子节点的值都要小。这就是所谓的“堆属性”,并且这个属于对堆中的每一个节点都成立。Java PriorityQueue默认最小堆 +初始化:PriorityQueue pq = new PriorityQueue<>(); +默认最小堆,初始化一个一个加是O(n log n), 一次很多数O(n) +常用方法: + pq.offer(2); //时间复杂度 O(log n); + pq.add(0); //时间复杂度 O(log n); + pq.add(1): + pq.peek(); // return 0 时间复杂度 O(1) + pq.poll(); // return 0 时间复杂度 O(log n) + pq.poll(); // return 1 时间复杂度 O(log n) +