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 10
思路1:
因为数组是有序的,所以最后返回的n个元素也一定是有序的,最后返回的是一个长度为k的子数组,也就是从n个元素的数组中去掉n-k个元素,且去掉的元素肯定从数组两头开始去,因为距离x最远的元素肯定在首尾出现。
实现1:
import java.util.List;
import java.util.ArrayList;
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> ret=new ArrayList<Integer>();
int len=arr.length;
int left=0,right=len-1;
while(len>k){
if(Math.abs(x-arr[left])>Math.abs(arr[right]-x)){
left++;
}else{
right--;
}
len--;
}
for(int i=left;i<=right;i++){
ret.add(arr[i]);
}
return ret;
}
}
思路2:
参考https://blog.csdn.net/TheSnowBoy_2/article/details/77441914
特殊情况:k个最近的元素都出现在数组的最左端或者都出现在最右端
通常,我们认为x出现在数组的中间,
假如我们取了 A[i] ~ A[i + k -1].
我们可以二分查找 i 计算 x - A[mid]和 A[mid +k] - x的距离
如果x - A[mid] > A[mid + k] - x, 那就意味着 A[mid + 1] ~ A[mid + k] 肯定比 A[mid] ~ A[mid + k - 1]距离x更近,此时我们让left = mid + 1.
实现2:
import java.util.List;
import java.util.ArrayList;
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> list=new ArrayList<Integer>();
int left=0,right=arr.length-k;
while(left<right){
int mid=left+(right-left)/2;
if(Math.abs(x-arr[mid])>Math.abs(arr[mid+k]-x)){
left=mid+1;//mid到x的距离大于mid+k到x的距离,右移
}else{
right=mid;//否则,左移
}
}
for(int i=left;i<left+k;i++){
list.add(arr[i]);
}
return list;
}
}