Given a list of sorted characters letters
containing only lowercase letters, and Given a target letter target
, find the Smalle St element in the list is larger than the given target.
Letters also wrap around. For example, if the target was target = ‘z‘
letters = [‘a‘, ‘b‘]
and, 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
Have a length in range [2, 10000]
.
letters
Consists of lowercase letters, and contains at least 2 unique letters.
target
is a lowercase letter.
The topic is a variant version of the binary lookup, the index of the returned value character array with the sizes to get rid of the target than all the characters.
1 CharNextgreatestletter (Char* Letters,intLetterssize,Chartarget) {2 intlow=0, high=letterssize;3 while(low<High ) {4 intmid=low+ (high-low)/2;5 if(Letters[mid]>target) High=mid;//if it's bigger than the target, go to the left.6 ElseLow=mid+1;//if it's smaller than the target, push it to the right.7 }8 /*L9 because the Etters array index range is 0-letterssize-1, when Low is greater than lettersSize-1,Ten Description Character Array there is no larger than the target character, at this time low==letterssize, the letterssize to take the remainder, One returns the first element of a character array. A */ - returnletters[low%Letterssize]; -}
744. Find Smallest letter Greater Than Target