【LeetCode刷题】744. 寻找比目标字母大的最小字母

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

给你一个排序后的字符列表 letters ,列表中只包含小写英文字母。另给出一个目标字母 target,请你寻找在这一有序列表里比目标字母大的最小字母。
在比较时,字母是依序循环出现的。举个例子:
如果目标字母target = 'z'并且字符列表为letters = ['a', 'b'],则答案返回'a'

示例:

输入:
letters = ["c", "f", "j"]
target = "a"
输出: "c"

输入:
letters = ["c", "f", "j"]
target = "c"
输出: "f"

输入:
letters = ["c", "f", "j"]
target = "d"
输出: "f"

输入:
letters = ["c", "f", "j"]
target = "g"
输出: "j"

输入:
letters = ["c", "f", "j"]
target = "j"
输出: "c"

输入:
letters = ["c", "f", "j"]
target = "k"
输出: "c"

题解

语言:C++
思路:二分法

class Solution {
public:
    char nextGreatestLetter(vector<char>& letters, char target) {
        int l = 0;
        int r = letters.size() - 1;
        if(letters[r] <= target){
            return letters[l];
        }
        while(l < r){
            int mid = l + r >> 1;
            if(letters[mid] > target){
                r = mid;
            }else{
                l = mid + 1;
            }
        }
        return letters[l] > target ? letters[l] : letters[l+1];
    }
};
上一篇:Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value &


下一篇:《R语言编程艺术》——2.5 使用all()和any()