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:

  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);
    }








版权声明:本文为sundawei2016原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。