LeetCode 744. 寻找比目标字母大的最小字母

题目链接:

力扣icon-default.png?t=M3K6https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/

【分析】二分查找第一个大于target的元素,需要注意当target

class Solution {

    public int binarySearch(char[] letters, char target){
        int left = 0, right = letters.length - 1, mid;
        while(left <= right){
            mid = (left + right) >>> 1;
            if(target < letters[mid]) right = mid - 1;
            else left = mid + 1;
        }
        return left;
    }

    public char nextGreatestLetter(char[] letters, char target) {
        int idx = binarySearch(letters, target);
        return letters[idx % letters.length];
    }
}

你可能感兴趣的:(LeetCode,leetcode,二分查找)