如果能明确的确定要返回的值是什么,用三个判断,用下面这套模版,例如 704. Binary Search:

    public int search(int[] nums, int target) {
        int l=0, r = nums.length-1, mid=0, res = -1;while(l<=r){
            mid = (l+r)/2;
            if(条件1)
                return mid;  //找到了,返回mid
            else if(条件2){
                l=mid+1;     //往后找
            }else{
                r = mid-1;   //往前找
            }
        }
        return -1;          //如果没找到
    }

如果求最大或者最小值,用三个判断,例如 1891. Cutting Ribbons, 模版如下

   public int maxLength(int[] ribbons, int k) {int l = 1, r = max, mid = l, res = 0;
       while(l <= r){
           mid = (l+r)/2;
           if(cutRibben(ribbons, mid, k)){ //满足条件
               l = mid+1;    往后找
               res = mid;    先把mid给res
           }
           else
               r = mid-1;   往前找
       }
       return res;         返回结果
    }

 

 

如果不能明确返回的值是什么,只能让l和r无限接近,当l和r相等的时候,就是想要的结果,那么用下面这套模版, 例如 540. Single Element in a Sorted Array

    public int singleNonDuplicate(int[] nums) {
        int l = 0, r = nums.length - 1, mid = 0;
        while (l < r) {
            mid = (l + r) / 2;
            if (条件1) {
                if (mid % 2 == 1)    //往后或者往前找或者l/r = mid
                    l = mid + 1;
                else
                    r = mid;
            } else if (条件2) {
                if (mid % 2 == 1) {  //往后或者往前找或者l/r = mid
                    r = mid - 1;
                } else
                    l = mid;
            }
        }
        return nums[l];            //l或r都是要找的结果,因为这个时候l=r
    }

 

posted on 2022-01-18 15:44  阳光明媚的菲越  阅读(41)  评论(0编辑  收藏  举报