MaxPriorityQueue [最大优先队列]
# 介绍
最大优先队列实际就是一个大顶堆,即每次插入堆中的元素,都存储至堆末端,通过上浮操作比较,大于父节点则和父节点交换元素,直到根结点为止,这样就形成了一个大顶堆。在获取最大值时,由于堆是数组的结构,只需获取根结点的值,即数组下标为 1 的值即可。获取最大值并删除,则可以交换根结点和尾结点,之后删除尾结点,并对根结点进行下沉操作,保证每个父节点都大于两个左右子树即可。
# 实现
# JavaScript
const { Heap, MaxHeap } = require('@datastructures-js/heap');
const getMaxCompare = (getCompareValue) => (a, b) => {
const aVal = typeof getCompareValue === 'function' ? getCompareValue(a) : a;
const bVal = typeof getCompareValue === 'function' ? getCompareValue(b) : b;
return aVal < bVal ? 1 : -1;
};
/**
* @class MaxPriorityQueue
* @extends MaxHeap
*/
class MaxPriorityQueue {
constructor(getCompareValue, _heap) {
if (getCompareValue && typeof getCompareValue !== 'function') {
throw new Error('MaxPriorityQueue constructor requires a callback for object values');
}
this._heap = _heap || new MaxHeap(getCompareValue);
}
/**
* Returns an element with highest priority in the queue
* @public
* @returns {number|string|object}
*/
front() {
return this._heap.root();
}
/**
* Returns an element with lowest priority in the queue
* @public
* @returns {number|string|object}
*/
back() {
return this._heap.leaf();
}
/**
* Adds a value to the queue
* @public
* @param {number|string|object} value
* @returns {MaxPriorityQueue}
*/
enqueue(value) {
return this._heap.insert(value);
}
/**
* Removes and returns an element with highest priority in the queue
* @public
* @returns {number|string|object}
*/
dequeue() {
return this._heap.extractRoot();
}
/**
* Returns the number of elements in the queue
* @public
* @returns {number}
*/
size() {
return this._heap.size();
}
/**
* Checks if the queue is empty
* @public
* @returns {boolean}
*/
isEmpty() {
return this._heap.isEmpty();
}
/**
* Clears the queue
* @public
*/
clear() {
this._heap.clear();
}
/**
* Returns a sorted list of elements from highest to lowest priority
* @public
* @returns {array}
*/
toArray() {
return this._heap.clone().sort().reverse();
}
/**
* Creates a priority queue from an existing array
* @public
* @static
* @returns {MaxPriorityQueue}
*/
static fromArray(values, getCompareValue) {
const heap = new Heap(getMaxCompare(getCompareValue), values);
return new MaxPriorityQueue(
getCompareValue,
new MaxHeap(getCompareValue, heap).fix()
);
}
}
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
编辑 (opens new window)
上次更新: 2022/10/11, 17:42:20