二分查找 (Binary Search)

 

思路:双指针二分查找

// @Title: 二分查找 (Binary Search)
// @Author: qisiii
// @Date: 2022-02-26 11:51:15
// @Runtime: 0 ms
// @Memory: 42.1 MB
// @comment: 双指针二分查找
// @flag: BLUE
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;
            if(nums[mid]==target){
                return mid;
            }else if(nums[mid]>target){
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }

}

思路:

// @Title: 二分查找 (Binary Search)
// @Author: qisiii
// @Date: 2022-02-20 11:24:01
// @Runtime: 0 ms
// @Memory: 42.1 MB
// @comment: 
// @flag: 
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;
            if (nums[mid]==target){
                return mid;
            }else if(nums[mid]>target){
                right=mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }
}

思路:递归似二分

// @Title: 二分查找 (Binary Search)
// @Author: qisiii
// @Date: 2023-05-18 23:59:23
// @Runtime: 0 ms
// @Memory: 44 MB
// @comment: 递归似二分
// @flag: GREEN
class Solution {
    public int search(int[] nums, int target) {
        return erfen(nums,0,nums.length-1,target);
    }
    private static int erfen(int[] nums,int left,int right,int target){
        if(left==right&&nums[left]!=target){
            return -1;
        }
        int middle=left+(right-left)/2;
        if(nums[middle]>target){
            return erfen(nums,left,middle,target);
        }else if (nums[middle]<target){
            return erfen(nums,middle+1,right,target);
        }else{
            return middle;
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18