From c571bcfc078e899a7561132db6b64bbbdb5f6f73 Mon Sep 17 00:00:00 2001 From: Tim Bradley Date: Fri, 3 Mar 2023 06:55:48 -0700 Subject: [PATCH] Optimize baseline and special case performance for kSmallest (#37) * Optimize baseline and special case performance for kSmallest * PR feedback: check k earlier, simplify conditional --- FastPriorityQueue.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/FastPriorityQueue.js b/FastPriorityQueue.js index a78dabe..4a643c5 100644 --- a/FastPriorityQueue.js +++ b/FastPriorityQueue.js @@ -285,15 +285,17 @@ FastPriorityQueue.prototype.forEach = function(callback) { // runs in O(k log k) time, the elements are not removed // from the priority queue. FastPriorityQueue.prototype.kSmallest = function(k) { - if (this.size == 0) return []; + if ((this.size == 0) || (k<=0)) return []; k = Math.min(this.size, k); - var fpq = new FastPriorityQueue(this.compare); - const newSize = Math.min((k > 0 ? Math.pow(2, k - 1) : 0) + 1, this.size); + const newSize = Math.min(this.size, (1 << (k - 1)) + 1); + if (newSize < 2) { return [this.peek()] } + + const fpq = new FastPriorityQueue(this.compare); fpq.size = newSize; fpq.array = this.array.slice(0, newSize); - var smallest = new Array(k); - for (var i = 0; i < k; i++) { + const smallest = new Array(k); + for (let i = 0; i < k; i++) { smallest[i] = fpq.poll(); } return smallest;