[LeetCode] 744. Find Smallest Letter Greater Than Target_Easy tag: Binary Search
2018-08-20 02:46 Johnson_强生仔仔 阅读(171) 评论(0) 编辑 收藏 举报Given a list of sorted characters letters
containing only lowercase letters, and given a target letter target
, find the smallest element in the list that is larger than the given target.
Letters also wrap around. For example, if the target is target = 'z'
and letters = ['a', 'b']
, the answer is 'a'
.
Examples:
Input: letters = ["c", "f", "j"] target = "a" Output: "c" Input: letters = ["c", "f", "j"] target = "c" Output: "f" Input: letters = ["c", "f", "j"] target = "d" Output: "f" Input: letters = ["c", "f", "j"] target = "g" Output: "j" Input: letters = ["c", "f", "j"] target = "j" Output: "c" Input: letters = ["c", "f", "j"] target = "k" Output: "c"
Note:
letters
has a length in range[2, 10000]
.letters
consists of lowercase letters, and contains at least 2 unique letters.target
is a lowercase letter.
思路for loop letters, 一旦有ord(c) > ord(target), 返回c, 否则返回letter c. 因为是non- decreasing order
O(n)
Code
class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: for c in letters: if ord(c) > ord(target): return c return letters[0]
Binary search, change letter into index using ord() method, also deal with edge case first 如果ord(target) 比第一个小或者跟最后一个相等或者更大,返回letters[0], 其他的就找first index s.t ord(letters[index]) > ord(target)
O( lg n)
class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: index_target = ord(target) if index_target >= ord(letters[-1]) or index_target < ord(letters[0]): return letters[0] l, r = 0, len(letters) - 1 while l + 1 < r: mid = l + (r - l)//2 index = ord(letters[mid]) if index > index_target: r = mid else: l = mid return letters[r] # 因为letters[l] 总会<=target, edge case 也排除了