区间查找

 public static void main(String[] args) {
        int[] a1 = {-1, 2, 90, 90, 90, 100, 207};
        int start = left_boud(a1, 90);
        int end = right_boud(a1, 90);
        System.out.println(MessageFormat.format("start:{0}, end:{1}", start, end));

    }

    static int left_boud(int[] array, int target) {
        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (array[mid] == target) {
                if (mid == 0 || array[mid - 1] < target) {
                    return mid;
                }
                end = mid - 1;
            } else if (array[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }

    static int right_boud(int[] array, int target) {
        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (array[mid] == target) {
                if (mid == array.length - 1 || array[mid + 1] > target) {
                    return mid;
                }
                start = mid + 1;
            } else if (array[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }

你可能感兴趣的:(区间查找)