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
题目
思路
本题要求我们在sorted array中找出K个最相近于x的数。因为输出结果一定排好序的、k-size的区间,若能找出该区间的leftBound,向右边走k个值,就可以得到desired output。
即问题转化为,怎样找到该leftBound呢? 在[0, n-k]中使用binary search查找
代码
1 class Solution { 2 public List<Integer> findClosestElements(int[] arr, int k, int x) { 3 int begin = 0; 4 int end = arr.length - k; 5 while(begin < end){ 6 int mid = begin + (end - begin) /2 ; 7 if(x > arr[mid]){ 8 if( x - arr[mid] > arr[mid + k] - x){ 9 begin = mid +1; 10 }else{ 11 end = mid; 12 } 13 }else{ 14 end = mid; 15 } 16 } 17 int index = begin; 18 List<Integer> result = new ArrayList<>() ; 19 while( k != 0){ 20 result.add(arr[index++]); 21 k--; 22 } 23 return result; 24 } 25 }