给定一串只含有小写形式的、排序过的 letters
,并且给定一个目标字母 target
,请找出在给定字母串中,大于目标字母的最小的那一个字母。
在本题中,字母是绕回编址的(即“z”后一位重新变为“a”)。比如说,如果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"
注意事项
1.letters
长度范围为 [2, 10000]
.
2.letters
只含有小写字母,并且其中至少含有两个互不相同的字母。
3.target
也是一个小写字母。
解题思路:
看到有序就想到二分查找,此题先处理特殊情况后,可应用二分查找。
public class Solution {
/**
* @param letters: a list of sorted characters
* @param target: a target letter
* @return: the smallest element in the list that is larger than the given target
*/
public char nextGreatestLetter(char[] letters, char target) {
// Write your code here
//若目标字符比数组中最大的元素还要大,则直接返回最小的字母
if(letters[letters.length-1] <= target)
return letters[0];
int l = 0;
int r = letters.length-1;
while(l < r){
int mid = l + (r-l)/2;
if(letters[mid] <= target)
l = mid + 1;
else
r = mid;
}
return letters[l];
}
}