LeetCode 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:
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:
- 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
题目大意:
给定一个排序数组,两个整数k和x,求数组中距离x最近的k个数字。结果应该有序,距离相同时优先选择较小的数字。
解题思路:
- 进阶二分法找出第一个大于等于key值的元素。
- 左右两指针搜索k个元素。
注意事项:
- 指针不能越界
- 根据题意,与key距离一样时,取较小元素。
Java代码:
1 | public List<Integer> findClosestElements(int[] arr, int k, int x) { |
算法分析:
时间复杂度为O(logn+k)
,空间复杂度O(1)
。