问题

  • k Closest position of Target

    • run 不出来

    • k只要大于零,那就一直

public class JavaApplication43 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] array = new int[]{1, 2, 3, 5, 7};
        int target = 3;
        int k = 2;
        JavaApplication43 app = new JavaApplication43();
        List<Integer> firstIndex = app.binarySearch(array, target, k);
        System.out.println(firstIndex);

    }

    public List<Integer> binarySearch(int[] arr, int target, int k) {
        //corner case
        List<Integer> ans = new ArrayList<>();
        if (arr == null || arr.length == 0 || k <= 0 ) {
            return ans;
        }

        int left = 0;
        int right = arr.length - 1;
        while (k-- > 0) {
            while (left < right + 1) {
                int mid = left + (right - left) / 2;
                if (arr[mid] == target) {
                    ans.add(arr[mid]);
                }
                if (arr[mid] < target) {
                    left = mid;
                } else {
                    right = mid;
                }
            }
            ans.add((Math.abs(arr[left] - target) < Math.abs(arr[right] - target)) ? arr[left] : arr[right]);
        
        }
        return ans;

    }

}

Last updated

Was this helpful?