Skip to content

Commit cc982b0

Browse files
committedMar 8, 2025
Add solution #658
1 parent a036ae3 commit cc982b0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,7 @@
495495
654|[Maximum Binary Tree](./0654-maximum-binary-tree.js)|Medium|
496496
655|[Print Binary Tree](./0655-print-binary-tree.js)|Medium|
497497
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|
498499
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
499500
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
500501
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

0 commit comments

Comments
 (0)