Skip to content

Commit 79bcb02

Browse files
authored
Update 658-find-k-closest-elements.js
1 parent 0d0f7ac commit 79bcb02

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

658-find-k-closest-elements.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,27 @@ const findClosestElements = function(arr, k, x) {
1616
}
1717
return arr.slice(lo, lo+k);
1818
};
19+
20+
// another
21+
22+
/**
23+
* @param {number[]} arr
24+
* @param {number} k
25+
* @param {number} x
26+
* @return {number[]}
27+
*/
28+
const findClosestElements = function(arr, k, x) {
29+
let lo=0,hi=arr.length-1
30+
while(hi-lo>=k){
31+
let left=Math.abs(x-arr[lo])
32+
let right=Math.abs(x-arr[hi])
33+
if(left<right){
34+
hi--
35+
}else if(left>right){
36+
lo++
37+
}else{
38+
hi--
39+
}
40+
}
41+
return arr.slice(lo,hi+1)
42+
};

0 commit comments

Comments
 (0)