UNPKG

2.65 kBMarkdownView Raw
1#二叉堆 Heap\<T>
2
3二叉堆是一种特殊的堆,二叉堆是完全二元树(二叉树)或者是近似完全二元树(二叉树)。二叉堆有两种:最大堆和最小堆。最大堆:父结点的键值总是大于或等于任何一个子节点的键值;最小堆:父结点的键值总是小于或等于任何一个子节点的键值。
4![Heap](https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=74466a96fad3572c72ef948eeb7a0842/77c6a7efce1b9d16836da71efbdeb48f8c546422.jpg)
5
6
7### api适用于最大堆和最小堆,此api以最大堆为例
8## 基本操作的API及示例
9
10### Constructor
11##### new MaxHeap(key ?: keyof T)
12``` text
13实例:
14const MaxHeap = new MaxHeap();
15
16const MaxHeap = new MaxHeap<{key:number}>("key");
17```
18
19### 插入 add
20##### MaxHeap add(T value)
21``` text
22实例:
23const maxHeap = new MaxHeap();
24maxHeap.add(1);
25maxHeap.add(2);
26maxHeap.add(3);
27```
28
29### 取堆顶 poll
30##### poll(): T
31``` text
32实例:
33const maxHeap = new MaxHeap();
34maxHeap.add(1);
35maxHeap.add(2);
36maxHeap.add(3);
37
38const value = maxHeap.poll();
39console.log(value);
40// 3
41```
42
43### 删除 remove
44##### remove(item: ((item: T) => boolean)|T): boolean
45``` text
46实例:
47const maxHeap = new MaxHeap();
48maxHeap.add(1);
49maxHeap.add(2);
50maxHeap.add(3);
51
52maxHeap.remove(2);
53maxHeap.remove(item => item === 3);
54```
55
56### 查看堆顶 peek
57##### peek(): T
58``` text
59实例:
60const maxHeap = new MaxHeap();
61maxHeap.add(1);
62maxHeap.add(2);
63maxHeap.add(3);
64
65const value = maxHeap.peek();
66console.log(value);
67// 3
68
69描述:
70不影响堆结构
71```
72
73### 是否为空 isEmpty
74##### isEmpty(): boolean
75``` text
76实例:
77const maxHeap = new MaxHeap();
78maxHeap.add(1);
79maxHeap.add(2);
80maxHeap.add(3);
81
82const value = maxHeap.isEmpty();
83console.log(value);
84// false
85```
86
87### 查找 find
88##### find(): T
89``` text
90实例:
91const maxHeap = new MaxHeap();
92maxHeap.add(1);
93maxHeap.add(2);
94maxHeap.add(3);
95
96maxHeap.find(2);
97const value = maxHeap.find(item => item === 2);
98console.log(value);
99// 2
100```
101
102### 查找所有 findAll
103##### findAll(): T[]
104``` text
105实例:
106const maxHeap = new MaxHeap();
107maxHeap.add(1);
108maxHeap.add(2);
109maxHeap.add(3);
110
111const value = maxHeap.findAll(item => item > 1);
112console.log(value);
113// [1, 2]
114```
115
116
117### 清空 clear
118##### clear(): void
119``` text
120实例:
121const maxHeap = new MaxHeap();
122maxHeap.add(1);
123maxHeap.add(2);
124maxHeap.add(3);
125
126maxHeap.clear();
127console.log(maxHeap.Size);
128// 0
129```
130
131### 清空 entries
132##### entries(): T[]
133``` text
134实例:
135const maxHeap = new MaxHeap();
136maxHeap.add(1);
137maxHeap.add(2);
138maxHeap.add(3);
139
140const values = maxHeap.entries();
141console.log(values);
142// [1, 2, 3]
143```
\No newline at end of file