educative.io

Two window Solution

public List findClosestElements(int[] arr, int k, int x) {
int low = 0;
int high = arr.length-1;

    while(high-low>=k){
        
        if(Math.abs(x-arr[low])>Math.abs(x-arr[high]))
            low++;
        else
            high--;
    }
    // List<Integer> l = IntStream.of(arr).boxed().collect(Collectors.toList());;
    // l = l.subList(low, high+1);
    ArrayList<Integer> l = new ArrayList<Integer>();
    for(int i=low;i<=high;i++){
        l.add(arr[i]);
    }
    return l;
}