November 20, 2022

658. Find K Closest Elements

658. Find K Closest Elements

Binary Search. 提前一步停下来。

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> res = new ArrayList<>();
        int closest = findClosest(arr, x);
        
        int left = closest;
        int right = closest;
        while (k > 1) {
            if (left == 0) {
                right ++;
            } else if (right == arr.length - 1) {
                left --;
            } else if (arr[right + 1] - x < x - arr[left - 1]) {
                right ++;
            } else {
                left --;
            }
            k--;
        }
        for (int i = left; i <= right; i++) {
            res.add(arr[i]);
        }
        
        return res;
    }
    
    private int findClosest(int[] arr, int x) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right - 1) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == x) {
                return mid;
            } else if (arr[mid] > x) {
                right = mid;
            } else {
                left = mid;
            }
        }
        if (arr[right] - x >= x - arr[left]) {
            return left;
        } else {
            return right;
        }            
    }
}
comments powered by Disqus