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

题目:

思路:

【1】熟悉常规二分查找即可

代码展示:

//时间0 ms 击败 100%
//内存42.8 MB 击败 94.16%
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int l = 0, r = letters.length-1;
        while (l < r){
            int mid = (r-l)/2 + l;
            if (letters[mid] == target){
                while (mid + 1 < letters.length && letters[mid+1] == target){
                    mid++;
                }
                //如果存在某字符等于目标字符,则应该返回右边第一个字符
                return (mid + 1) >= letters.length ? letters[0] : letters[mid + 1];
            }else if (letters[mid] > target){
                r = mid;
            }else {
                l = mid + 1;
            }
        }
        return letters[l] > target ? letters[l] : letters[0];
    }
}

//时间0 ms 击败 100%
//内存42.8 MB 击败 93.14%
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int length = letters.length;
        if (target >= letters[length - 1]) {
            return letters[0];
        }
        int low = 0, high = length - 1;
        while (low < high) {
            int mid = (high - low) / 2 + low;
            if (letters[mid] > target) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        return letters[low];
    }
}

 

posted @ 2023-08-16 19:03  忧愁的chafry  阅读(4)  评论(0编辑  收藏  举报