Example: Find K Closest Elements - rFronteddu/general_wiki GitHub Wiki

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

|a - x| < |b - x|, or |a - x| == |b - x| and a < b

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        if (arr == null || arr.length == 0) {
            return Collections.emptyList();
        }
        
        int index = findIndex(arr, x);
        List<Integer> result = new ArrayList<>(k);
       
        int left = index;
        int right = index + 1;
         
        while (k != 0) {
            if (left < 0) {
                result.add(arr[right]);
                right++;
            } else if (right == arr.length) {
                result.add(arr[left]);
                left--;
            } else if((Math.abs(arr[left] - x) < Math.abs(arr[right] - x)) || 
                      ((Math.abs(arr[left] - x) == Math.abs(arr[right] - x)) && (arr[left] < arr[right]))) {
                result.add (arr[left]);
                left--;
            } else {
                result.add (arr[right]);
                right++;
            }
            k--;
        }
        Collections.sort(result);
        return result;
      
    }
    
    int findIndex(int[] arr, int x) {
        int closestIndex = -1;
        int left = 0;
        int right = arr.length - 1;
        
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == x) {
                return mid;
            } else if (arr[mid] > x) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
            
            // Update closestIndex based on the distance to x
            if (closestIndex == -1 || Math.abs (arr[mid] - x) < Math.abs (arr[closestIndex] - x) ||
                (Math.abs (arr[mid] - x) == Math.abs (arr[closestIndex] - x) && 
                 arr[mid] < arr[closestIndex])) {
                closestIndex = mid;
            }
        }
        return closestIndex;
    }
}
⚠️ **GitHub.com Fallback** ⚠️