File tree 2 files changed +38
-0
lines changed
2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 495
495
654|[ Maximum Binary Tree] ( ./0654-maximum-binary-tree.js ) |Medium|
496
496
655|[ Print Binary Tree] ( ./0655-print-binary-tree.js ) |Medium|
497
497
657|[ Robot Return to Origin] ( ./0657-robot-return-to-origin.js ) |Easy|
498
+ 658|[ Find K Closest Elements] ( ./0658-find-k-closest-elements.js ) |Medium|
498
499
680|[ Valid Palindrome II] ( ./0680-valid-palindrome-ii.js ) |Easy|
499
500
684|[ Redundant Connection] ( ./0684-redundant-connection.js ) |Medium|
500
501
686|[ Repeated String Match] ( ./0686-repeated-string-match.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 658. Find K Closest Elements
3
+ * https://leetcode.com/problems/find-k-closest-elements/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a sorted integer array arr, two integers k and x, return the k closest integers to x
7
+ * in the array. The result should also be sorted in ascending order.
8
+ *
9
+ * An integer a is closer to x than an integer b if:
10
+ * - |a - x| < |b - x|, or
11
+ * - |a - x| == |b - x| and a < b
12
+ */
13
+
14
+ /**
15
+ * @param {number[] } arr
16
+ * @param {number } k
17
+ * @param {number } x
18
+ * @return {number[] }
19
+ */
20
+ var findClosestElements = function ( arr , k , x ) {
21
+ let left = 0 ;
22
+ let right = arr . length - k ;
23
+
24
+ while ( left < right ) {
25
+ const middle = Math . floor ( ( left + right ) / 2 ) ;
26
+ const x1 = arr [ middle ] ;
27
+ const x2 = arr [ middle + k ] ;
28
+
29
+ if ( x - x1 > x2 - x ) {
30
+ left = middle + 1 ;
31
+ } else {
32
+ right = middle ;
33
+ }
34
+ }
35
+
36
+ return arr . slice ( left , left + k ) ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments