力扣算法入门题库之二分法

int search(int* nums, int numsSize, int target){
    int left=0,right=numsSize-1,middle=left+(right-left)/2;
 while(left<=right){      //[left,right]不能写成(left(left,right)
       if(target==nums[middle])
            return middle;
        else if (target>nums[middle]){
                left=middle+1;
                middle=left+(right-left)/2;  //防止内存溢出
            }
            else{
                right=middle-1;
                middle=left+(right-left)/2;
            }
    }
               
   
     return -1;
   
}

总结:

1.做整型加法时要避免内存溢出;

2.二分法重要的一点是target的定义区间是[left,right]还是(left,right),这决定了while循环的判断条件是什么样的;

你可能感兴趣的:(二分法,算法,leetcode)