Description
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’.
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.
Example
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”
Submissions
解题思路利用二分法。题目要求返回列表中比目标字母大的最小字母,当letters[mid] <= target时,说明题目目标值在mid索引的右边,因此left更新为mid+1。否则,说明题目目标值在mid索引的左边,因此left更新为mid-1,需要注意mid-1索引上的数的值和target的大小,如果小于target的话就直接返回mid上的值。同时还要考虑到mid如果小于1时,就不存在mid-1,所以如果mid小于1,直接返回mid。
最后如果二分法查找完毕都没有题目目标值,则说明target比letters中的数都要大,按题目要求,返回第0个索引上的数。
并且在python3中需要注意,在mid = (left + right)//2中,‘//’代表向下取整,返回int型;‘/’代表精确除法,返回float型。
实现代码如下:
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
left, right = 0, len(letters)-1
while left <= right:
mid = (left + right)//2
if letters[mid] <= target:
left = mid + 1
else:
if mid < 1 or (mid >= 1 and letters[mid-1]<= target):
return letters[mid]
right = mid - 1
return letters[0]