Skip to content

Commit c571bcf

Browse files
authored
Optimize baseline and special case performance for kSmallest (#37)
* Optimize baseline and special case performance for kSmallest * PR feedback: check k earlier, simplify conditional
1 parent 7b70143 commit c571bcf

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

FastPriorityQueue.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -285,15 +285,17 @@ FastPriorityQueue.prototype.forEach = function(callback) {
285285
// runs in O(k log k) time, the elements are not removed
286286
// from the priority queue.
287287
FastPriorityQueue.prototype.kSmallest = function(k) {
288-
if (this.size == 0) return [];
288+
if ((this.size == 0) || (k<=0)) return [];
289289
k = Math.min(this.size, k);
290-
var fpq = new FastPriorityQueue(this.compare);
291-
const newSize = Math.min((k > 0 ? Math.pow(2, k - 1) : 0) + 1, this.size);
290+
const newSize = Math.min(this.size, (1 << (k - 1)) + 1);
291+
if (newSize < 2) { return [this.peek()] }
292+
293+
const fpq = new FastPriorityQueue(this.compare);
292294
fpq.size = newSize;
293295
fpq.array = this.array.slice(0, newSize);
294296

295-
var smallest = new Array(k);
296-
for (var i = 0; i < k; i++) {
297+
const smallest = new Array(k);
298+
for (let i = 0; i < k; i++) {
297299
smallest[i] = fpq.poll();
298300
}
299301
return smallest;

0 commit comments

Comments
 (0)