Leetcode 658. Find K Closest Elements

来源:互联网 发布:yonex 网球拍 知乎 编辑:程序博客网 时间:2024/06/03 10:58

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=3Output: [1,2,3,4]

Example 2:

Input: [1,2,3,4,5], k=4, x=-1Output: [1,2,3,4]

Note:

  1. The value k is positive and will always be smaller than the length of the sorted array.
  2. Length of the given array is positive and will not exceed 104

  1. Absolute value of elements in the array and x will not exceed 104

使用 binary search 二分法 来找到 arr 里 x 所对应的 index, 如果 没有,idx = - (插入位置)- 1. 

1, 2, 4, 5   x = 3

idx = -3, 插入位置的idx 是 2, 所以返回 -2-1 = -3

接下来的思路是运用两个指针,i,j 
如果 j 到 头了 或 ( i 大于等于 0 and 右边比左边 大于或等于)i--
public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {        int idx = Collections.binarySearch(arr, x);        idx = idx < 0 ? -(idx + 1) : idx;        int j = idx, i = idx - 1;        while (k-- > 0) {            if (j >= arr.size() || (i >= 0 && Math.abs(x - arr.get(j)) >= Math.abs(x - arr.get(i)))) i--;            else j++;        }        return arr.subList(i + 1, j);    }







原创粉丝点击