Find K Closest Elements

public class Solution {
    /**
     * @param A: an integer array
     * @param target: An integer
     * @param k: An integer
     * @return: an integer array
     */
    public int[] kClosestNumbers(int[] A, int target, int k) {
        // write your code here

        // the way to solve it is find the last one closed to target and use two pointer to get K numberss
    	//used a helper function to avoid index out of boundary issue
    	//we only need to find the most loer closed one even thought there is a number same with target
    	//when there is a number same with target, when found the most lower close number, we set it to left,
    	//right to the one next two it, then it is the one same with target. then when we check which one is closer,
    	//right one will win.be carefull index out of bound issue
    	int point = 0;
        int start = 0, end = A.length -1;

        while(start +1 < end){
        	int mid = start + (end - start)/2;
        	if (A[mid] == target) {
        		end = mid;
        	}
        	else if (A[mid] < target) {
        		start = mid;
        	}else{
        		end = mid;
        	}

        }
        
        point = A[end] < target ? end : A[start] < target ? start: -1;
       //two point
        
       int left = point  , right = point+1;
       int[] res =new int[k];

       for (int i = 0; i < k ;++i ) {
           if(leftCloser(A,target,left,right)){
               res[i] = A[left];
               left--;
           } else{
               res[i] = A[right];
               right++;
           }
       }
       return res;

    }

    public boolean leftCloser(int [] A,int target, int left,int right){
        if(left < 0){
            return false;
        }
        
        if(right > A.length-1){
            return true;
        }
        
        return target - A[left] <= A[right] - target;
    }
}

Last updated