0704. Binary Search

704. Binary Search #

题目 #

给定一个n个元素有序的升序整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1

思路 #

保持consistency不变量。

代码 #

class Solution {
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length;
        while (left < right) {
            int medium = left + (right - left) / 2;
            if (nums[medium] == target) return medium;
            else if (nums[medium] > target) right = medium;
            else left = medium + 1;
        }
        return -1;
    }
}