二分法1-力扣-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];
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章