-
Notifications
You must be signed in to change notification settings - Fork 43
/
find-smallest-letter-greater-than-target.py
45 lines (42 loc) · 1.2 KB
/
find-smallest-letter-greater-than-target.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79137225
# IDEA : LINEAR SEARCH
class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
for letter in letters:
# can just do the alphabet ordering check via "<", ">"
# i.e. 'a' > 'c' ; 'b' < 'd'
if ord(letter) > ord(target):
return letter
return letters[0]
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/79137225
# IDEA : BINARY SEARCH
class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
index = bisect.bisect_right(letters, target)
return letters[index % len(letters)]
# V2
# Time: O(logn)
# Space: O(1)
import bisect
class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
i = bisect.bisect_right(letters, target)
return letters[0] if i == len(letters) else letters[i]