website/content/ChapterFour/0600~0699/0658.Find-K-Closest-Elements.md
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
Note:
UPDATE (2017/9/19): The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes.
给定一个排序好的数组,两个整数 k 和 x,从数组中找到最靠近 x(两数之差最小)的 k 个数。返回的结果必须要是按升序排好的。如果有两个数与 x 的差值一样,优先选择数值较小的那个数。
说明:
更新(2017/9/19): 这个参数 arr 已经被改变为一个整数数组(而不是整数列表)。 请重新加载代码定义以获取最新更改。
len(arr) - K (因为长度为 K 以后,正好右区间就到数组最右边了),在 [0,len(arr) - K] 这个区间中进行二分搜索。如果发现 a[mid] 与 x 距离比 a[mid + k] 与 x 的距离要大,说明要找的区间一定在右侧,继续二分,直到最终 low = high 的时候退出。逼出的 low 值就是最终答案区间的左边界。
package leetcode
import "sort"
// 解法一 库函数二分搜索
func findClosestElements(arr []int, k int, x int) []int {
return arr[sort.Search(len(arr)-k, func(i int) bool { return x-arr[i] <= arr[i+k]-x }):][:k]
}
// 解法二 手撸二分搜索
func findClosestElements1(arr []int, k int, x int) []int {
low, high := 0, len(arr)-k
for low < high {
mid := low + (high-low)>>1
if x-arr[mid] > arr[mid+k]-x {
low = mid + 1
} else {
high = mid
}
}
return arr[low : low+k]
}