其他分享
首页 > 其他分享> > 二分查找整理(左闭右闭写法)

二分查找整理(左闭右闭写法)

作者:互联网

1. 数组中没有重复值

// 非递归方式
public int binarySearch(int[] nums, int target){
    int left = 0, right = target.length -1;
    while(left <= right){
        int mid = left + (right - left) / 2;
        if(nums[mid] < target){ 
            left = mid + 1;
        } else if(nums[mid] > target) {
            right = mid - 1;
        } else {
            return mid;
        }
    }
    return left;
}

// 递归方式
public int binarySearch(int[] nums, int target, int left, int right){
    if(left > right){ 
        return left;
    }
    int mid = left + (right - left) / 2;
    if(nums[mid] < target){
        return binarySearch(nums, target, mid+1, right);
    } else if(nums[mid] > target){
        return binarySearch(nums, target, left, mid-1);
    } else {
        return mid;
    }
}

2. 数组中有重复值, 找到第一个出现的地方

// 非递归方式
public int binarySearchFirst(int[] nums, int target){
    int left = 0, right = target.length -1;
    while(left <= right){
        int mid = left + (right - left) / 2;
        if(nums[mid] < target){ 
            left = mid + 1;
        } else if (nums[mid] >= target) {
            right = mid - 1;
        }
    }
    return left;
}
//递归方式
public int binarySearchFirst(int[] nums, int target, int left, int right){
    if(left > right){
        return left;
    }
    int mid = left + (right - left) >> 1;
    if(nums[mid] < target){
        return binarySearchFirst(nums, target, mid+1, right);
    } else if(nums[mid] >= target){
        return binarySearchFirst(nums, target, left, mid-1);
    }
}

 

标签:二分,right,target,nums,int,mid,右闭,左闭,left
来源: https://blog.csdn.net/Jonny_ye/article/details/122281153