File tree Expand file tree Collapse file tree 1 file changed +7
-5
lines changed
Expand file tree Collapse file tree 1 file changed +7
-5
lines changed Original file line number Diff line number Diff 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.
287287FastPriorityQueue . 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 ;
You can’t perform that action at this time.
0 commit comments