美文网首页
658. Find K Closest Elements

658. Find K Closest Elements

作者: AThornBird | 来源:发表于2019-02-18 02:45 被阅读0次
class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        if (k == 0) {
             List<Integer> list = new ArrayList<Integer>();
             // list.add(0);
             return list;
        }
        
        int left = largestSmallerEqual(arr, x);
        int right = left + 1;
        int start = 0;
        int end = 0;
        List<Integer> result = new ArrayList<>(); 
        
        for(int i = 0; i < k ; i++) {       
            if(right >= arr.length || left >= 0 && Math.abs(x - arr[left]) <= Math.abs(arr[right] - x)) {
                start = left--;
            } else {
                end = right++;
            }
        }
        
        for(int j = start; j <= start + k - 1; j++) {
            result.add(arr[j]);
        }

        return result;
    }
    
    private int largestSmallerEqual(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) {
                left = mid;
            } else {
                right = mid;
            }
        }
        if (arr[right] <= x){
            return right;
        }
        if (arr[left] <= x) {
            return left;
        }
        return 0;        
    }
}

相关文章

网友评论

      本文标题:658. Find K Closest Elements

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