658. Find K Closest Elements
Medium
Given a sorted integer array arr
, two integers k
and x
, return the k
closest integers to x
in the array. The result should also be sorted in ascending order.
An integer a
is closer to x
than an integer b
if:
|a - x| < |b - x|
, or|a - x| == |b - x|
anda < b
Example 1:
Example 2:
Constraints:
1 <= k <= arr.length
1 <= arr.length <= 104
arr
is sorted in ascending order.-104 <= arr[i], x <= 104
解題
給的 arr
是一個排序好的陣列,而數字 k 的值可能會有:小於陣列所有數字、大於陣列所有數字、在陣列最小數與最大數之間 這三種可能。第一種可能的話,最遠的值會集中在陣列末端;第二種可能的話,最遠的值最集中在陣列首;第三種可能則首尾都可能。所以我們可以從首尾開始檢查,每次都移除一個最遠的,直到留下 k 個最近的數字。
Runtime: 44 ms, faster than 89.61%
Memory Usage: 6.8 MB, less than 93.85%
Last updated