leetcode 744.寻找比目标字母大的最小字母(Java 二分查找 easy)

https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/submissions/

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int n=letters.length;
        int l=0,h=n-1;
        while(l<=h){
            int mid=l+(h-l)/2;
            if(letters[mid]<=target){//因为是求大于target的最小值,所以此处是小于等于。
                l=mid+1;//小于等于的时候l=mid+1。
            }else{
                h=mid-1;
            }
        }
        return l<n ? letters[l] : letters[0];//如果target比序列里所有值都大,返回第一个。
    }
}

猜你喜欢

转载自www.cnblogs.com/y1040511302/p/11575062.html