算法刷题-数组

704 二分查找

class Solution {
    public int search(int[] nums, int target) {

         //区间左闭右闭
        int left=0;
        int right=nums.length-1;
        while(left<=right){//等号是有意义的
            int mid=left+(right-left)/2;// (left + right)/2可能会溢出, left + (right - left) /2就不会溢出
            if(target==nums[mid]){
                return mid;
            }else if(nums[mid]>right){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
    return -1;
    }
}

你可能感兴趣的:(算法打卡,java,算法)