美文网首页poi word 目录生成
leetcode658+有序数组找出距离数字x最近的k个数字

leetcode658+有序数组找出距离数字x最近的k个数字

作者: 寻Sweet | 来源:发表于2019-12-24 12:44 被阅读0次

    在一个非递减数组中,找到距离目标值,最近的数组索引。
    如 1 2 3 6 7 8 ,目标值为4
    返回 2

    思路:
    可以理解为 先用二分法找到这个目标值,如果找不到,那么就找它应该插入的顺序,判断插入顺序两边的元素谁和目标值近。

    image.png

    //中级
    public class Solution {
    public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
    int n = arr.size();
    if (x <= arr.get(0)) {
    return arr.subList(0, k);
    } else if (arr.get(n - 1) <= x) {
    return arr.subList(n - k, n);
    } else {
    int index = Collections.binarySearch(arr, x);
    if (index < 0)
    index = -index - 1;
    int low = Math.max(0, index - k - 1), high = Math.min(arr.size() - 1, index + k - 1);

            while (high - low > k - 1) {
                if (low < 0 || (x - arr.get(low)) <= (arr.get(high) - x))
                    high--;
                else if (high > arr.size() - 1 || (x - arr.get(low)) > (arr.get(high) - x))
                    low++;
                else
                    System.out.println("unhandled case: " + low + " " + high);
            }
            return arr.subList(low, high + 1);
        }
    }
    

    }

    //高级
    public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
    Collections.sort(arr, (a,b) -> a == b ? a - b : Math.abs(a-x) - Math.abs(b-x));
    arr = arr.subList(0, k);
    Collections.sort(arr);
    return arr;
    }

    相关文章

      网友评论

        本文标题:leetcode658+有序数组找出距离数字x最近的k个数字

        本文链接:https://www.haomeiwen.com/subject/jkoxoctx.html