[LeetCode] 744. Find Smallest Letter Greater Than Target
作者:互联网
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.
寻找比目标字母大的最小字母。
给你一个排序后的字符列表 letters ,列表中只包含小写英文字母。另给出一个目标字母 target,请你寻找在这一有序列表里比目标字母大的最小字母。
在比较时,字母是依序循环出现的。举个例子:
如果目标字母 target = 'z' 并且字符列表为 letters = ['a', 'b'],则答案返回 'a'
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
最优解是二分法,当然线性的做法也是可以的。
这里有一个corner case需要判断,就是如果target字母 >= input数组的最后一个字母,那么我们返回的是input数组的首字母。其他环节都是正常的二分法判断。
时间O(logn)
空间O(1)
Java实现
1 class Solution { 2 public char nextGreatestLetter(char[] letters, char target) { 3 int len = letters.length; 4 // corner case 5 if (target >= letters[len - 1]) { 6 return letters[0]; 7 } 8 9 // normal case 10 int start = 0; 11 int end = len - 1; 12 while (start + 1 < end) { 13 int mid = start + (end - start) / 2; 14 if (letters[mid] - target > 0) { 15 end = mid; 16 } else { 17 start = mid; 18 } 19 } 20 if (letters[start] > target) { 21 return letters[start]; 22 } else { 23 return letters[end]; 24 } 25 } 26 }
标签:letters,target,字母,start,Output,744,Input,Find,Greater 来源: https://www.cnblogs.com/cnoodle/p/14275296.html