A typescript implementation of Priority Queue (based on min-heap) and Circular Queue.
Install
Usage
PriorityQueue
Priority Queue is a special queue structure, the first element of the queue always returns to the
minimum value in the queue, and the amortized time complexity of the enqueue and dequeue operations
are both $O(\log N)$.
CircularQueue
Circular queue is a queue structure, the main purpose of its design is to reuse space as much as
possible on the basis of ordinary queues. Circular queues usually need to specify the maximum volume
C of the collector. If the number of elements in the queue exceeds C, only the most recent C
elements are kept in the queue. Other operations are the same as ordinary queues.
Example
-
Basic -- PriorityQueue
import { PriorityQueue } = '@algorithm.ts/queue'
const Q = new PriorityQueue<number>({ compare: (x, y) => y - x })
Q.enqueue(3)
Q.enqueue(7)
Q.enqueue(-5)
Q.enqueue(1)
Q.size
Array.from(Q)
Q.dequeue()
Q.dequeue()
Q.front()
Q.front()
Q.dequeue()
Q.front()
Q.dequeue()
Q.front()
Q.dequeue()
-
Basic -- CircularQueue
import { CircularQueue } from '@algorithm.ts/queue'
const queue = new CircularQueue<{ name: string }>()
queue.init(100)
queue.enqueue({ name: 'alice' })
queue.enqueue({ name: 'bob' })
queue.size
queue.front()
queue.back()
queue.dequeue()
queue.size
-
A solution for 剑指offer#63 https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1
import { PriorityQueue } from '@algorithm.ts/queue'
const lowerQ = new PriorityQueue<number>({ compare: (x, y) => x - y })
const upperQ = new PriorityQueue<number>({ compare: (x, y) => y - x })
export function Insert(num: number): void {
if (lowerQ.size === upperQ.size) {
upperQ.enqueue(num)
lowerQ.enqueue(upperQ.dequeue()!)
} else {
lowerQ.enqueue(num)
upperQ.enqueue(lowerQ.dequeue()!)
}
}
export function GetMedian(): number {
return lowerQ.size === upperQ.size
? (lowerQ.front()! + upperQ.front()!) / 2
: lowerQ.front()!
}
Related