744. Find Smallest Letter Greater Than Target
阿新 • • 發佈:2018-10-18
title tle unique uniq greatest test pan char hat
.
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(low<high){ 4 int mid=low+(high-low)/2; 5 if(letters[mid]>target) 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 }
744. Find Smallest Letter Greater Than Target