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.
题目是变种版的二分查找,返回值字符数组的索引用取余搞定目标比所有字符大这个问题。
1 char nextGreatestLetter(char* letters, int lettersSize, char target) { 2 int low=0, high=lettersSize; 3 while(lowtarget) high=mid;//如果比目标大,就往左边找 6 else low=mid+1; //如果比目标小,就往右边推 7 } 8 /*l 9 因为etters数组索引范围是0-lettersSize-1,当low大于lettersSize-1的情况下,10 说明字符数组里面不存在比目标大的字符,此时low==lettersSize,对lettersSize进行取余,11 返回字符数组第一个元素。12 */13 return letters[low%lettersSize];14 }