658. Find K Closest Elements
题目描述
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:
|
|
Example 2:
|
|
Note:
- The value k is positive and will always be smaller than the length of the sorted array.
- Length of the given array is positive and will not exceed 104
- Absolute value of elements in the array and x will not exceed 104
题目大意
给定一个有序数组,在数组中找到与 x 接近的 k 个元素。
解题思路
使用二分查找找到最接近
x的数组下标index。
从子序列index-k...index+k中找到最接近x的k个元素。
代码
|
|