题目描述:
给你一个排序后的字符列表 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[left].
利用二分法自己定义一个默认规则,使用闭区间,初始值:left=0,right=nums.lenght-1
循环判断条件是while(left<=right)
left和right的更新条件是:left=mid+1;right=mid-1
代码:
class Solution { public char nextGreatestLetter(char[] letters, char target) { int n=letters.length; int left=0,right=n-1; while(left<=right){ int mid=left+(right-left)/2; if(target<letters[mid]){ right=mid-1; }else if(target>=letters[mid]){ left=mid+1; } } return left<n?letters[left]:letters[0]; } }