704. 二分查找 - 力扣(LeetCode) (leetcode-cn.com)

两种解题方案:

一、循环

public int search(int[] nums, int target) {
    int low = 0, high = nums.length - 1;
    while (low <= high) {
        int min = (high + low) / 2;
        if (nums[min] == target) {
            return min;
        } else if (target < nums[min]) {
            high = min - 1;
        } else {
            low = min + 1;
        }
    }
    return -1;
}

二、递归

public int search(int[] nums, int target) {
    int len = nums.length;
    return helper(nums, target, 0, len - 1);
}

public int helper(int[] nums, int target, int left, int right) {
    if (nums[left] > target || nums[right] < target) {
        return -1;
    }
    if (left > right) {
        return -1;
    }
    int index = (right + left) / 2;
    if (nums[index] == target) {
        return index;
    } else if (nums[index] > target) {
        return helper(nums, target, left, index - 1);
    } else {
        return helper(nums, target, index + 1, right);
    }
}