LeetCode 744. Find Smallest Letter Greater Than Target 2019-08-16

题目描述

给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。

数组里字母的顺序是循环的。举个例子,如果目标字母target = ‘z’ 并且有序数组为 letters = [‘a’, ‘b’],则答案返回 ‘a’。

letters长度范围在[2, 10000]区间内。letters 仅由小写字母组成,最少包含两个不同的字母。目标字母target 是一个小写字母。

tag

二分

样例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
输入:
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"

算法1

(二分) O(logn)
思路
复杂度分析:
python 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
l = len(letters)
left = 0
right = l - 1

while left < right:

mid = (left + right) // 2

if ord(letters[mid]) > ord(target):
right = mid
else:
left = mid + 1

if left < l - 1:
return letters[left]
elif left == l - 1 and ord(letters[left]) > ord(target):
return letters[left]
else:
return letters[0]