Easy to understand Java Solution


  • 0
    S
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
            List<Integer> ans = new ArrayList<>();
            int index = findClosestElementsHelper(arr,x);
            int leftIndex = index - 1, rightIndex = index + 1, n = arr.length;
            k--;
            while(k > 0){
                if(leftIndex < 0) rightIndex++;
                else if(rightIndex > n - 1) leftIndex--;
                else if(Math.abs(arr[leftIndex] - x ) <= Math.abs(arr[rightIndex] - x )) leftIndex--;
                else rightIndex++;
                k--;		
            }
            leftIndex++;
            rightIndex--;
            for(int i = leftIndex; i <= rightIndex; i++){
                ans.add(arr[i]);
            }
            return ans;
        }
        
        public int findClosestElementsHelper(int[] nums, int x){
            int low = 0, high = nums.length - 1;
            while(low < high){
                int mid = (low + high) / 2;
                if(nums[mid] == x) return mid;
                else if(nums[mid] > x) high = mid - 1;
                else low = mid + 1;
            }
            return low;
        }

Log in to reply
 

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