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个数字。结果应该有序,距离相同时优先选择较小的数字。
1 public List<Integer> findClosestElements(int[] arr, int k, int x) { 2 // 由于数组是有序的,所以最后返回的k个元素也一定是有序的,那么其实就是返回了原数组的一个长度为k的子数组,转化一下, 3 // 实际上相当于在长度为n的数组中去掉n-k个数字,而且去掉的顺序肯定是从两头开始去,应为距离x最远的数字肯定在首尾出现。 4 // 那么问题就变的明朗了,我们每次比较首尾两个数字跟x的距离,将距离大的那个数字删除,直到剩余的数组长度为k为止 5 List<Integer> list =new ArrayList<Integer>(); 6 for (int i=0;i<arr.length;i++) 7 { 8 list.add(arr[i]); 9 } 10 while (list.size() > k) { 11 int first = 0, last = list.size() - 1; 12 if (x - list.get(first) <= list.get(last) - x) { 13 list.remove(last); 14 } else { 15 list.remove(first); 16 } 17 } 18 return list; 19 }