Java O(n) time solution


  • 0
    A
    public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
            List<Integer> list = new ArrayList<Integer>();
            if(arr.size()==0 || k==0) return list;
            
            int start = 0, min = Math.abs(arr.get(start) - x);
            for(int i=k-1; i< arr.size(); i++) {
    
                if(Math.abs(arr.get(i) - x) < min ) {
                    start = i + 1 -k;
                    min = Math.abs(arr.get(start) - x);
                }
            }
            
            for(int i=start; i< start+k; i++) {
                list.add(arr.get(i));
            }
            
            return list;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.