# 744. 寻找比目标字母大的最小字母
力扣原题链接(点我直达) (opens new window)
给定一个只包含小写字母的有序数组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" 注:
letters长度范围在[2, 10000]区间内。 letters 仅由小写字母组成,最少包含两个不同的字母。 目标字母target 是一个小写字母。
# 二分法,比较绕一点了
char nextGreatestLetter(vector<char>& letters, char target) {
int l = 0;
int r = letters.size() - 1;
while (l <= r)
{
int mid = (l + r) / 2;
if (target < letters[mid])//确切大于了,右侧再向后退
r = mid - 1;
else
l = mid + 1;//即使是等于,也依然向前走
}
return letters[l % letters.size()];//到最后节点了,返回第一个元素
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
执行用时 :8 ms, 在所有 C++ 提交中击败了99.29%的用户
内存消耗 :9.1 MB, 在所有 C++ 提交中击败了78.92%的用户