二分法-力扣-java

//1 best
class Solution {
    public int mySqrt(int x) {
        if(x==0) return 0;
        if(x==1) return 1;
        int low=0,high=x;
        while(low<=high){
            int mid=low+(high-low)/2;
            if(x/mid==mid) return mid;
            else if(x/mid<mid) high=mid-1;
            else low=mid+1;
        }
        return high;
    }
}
//2
class Solution {
    public int mySqrt(int x) {
        long low=0;
        long high=x/2+1;
        while(low<=high){
            long mid=low+(high-low)/2;
            if(mid*mid<=x&&(mid+1)*(mid+1)>x)
                return (int) mid;
            else if(mid*mid>x) high=mid-1;
            else low=mid+1;    
        }
        return (int)high;
    }
}

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        for(char c:letters){
            if(c>target)
                return c;        
        }
        return letters[0];
    }
}

class Solution {
    public int singleNonDuplicate(int[] nums) {
        int low=0,high=nums.length-1;
        while(low<high){
            int mid=low+(high-low)/2;
            if(mid%2==1) mid--;          //防止mid是奇数
            if(nums[mid]==nums[mid+1])   //目标在[mid+2,h]
                low=mid+2;               //目标在[l,mid]
            else high=mid;    
        }
        return nums[high];
    }
}

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int low=1,high=n;
        while(low<high){
            int mid=low+(high-low)/2;
            if(isBadVersion(mid)) high=mid;
            else low=mid+1;
        }
        return high;
        
    }
}

class Solution {
    public int findMin(int[] nums) {
        int low=0,high=nums.length-1;
        while(low<high){
            int mid=low+(high-low)/2;
            if(nums[mid]>nums[high]) low=mid+1;
            else high=mid;
        }                 
        return nums[high];                        
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值