congr / world

2 stars 1 forks source link

LeetCode : 658. Find K Closest Elements #457

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/find-k-closest-elements/

image

congr commented 5 years ago

Bin search should be modified, NLogN

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> list = new ArrayList();

        int s = 0, e = arr.length-1;

        while(e - s >= k) { // !!! >=
            if (Math.abs(arr[s]-x) > Math.abs(arr[e]-x)) s++; // !!!
            else e--; // !!!
        }

        for(int i = s; i <= e; i++) list.add(arr[i]);
        return list;
    }
}