【LeetCode刷題】744. 尋找比目標字母大的最小字母
阿新 • • 發佈:2021-07-02
744. 尋找比目標字母大的最小字母
給你一個排序後的字元列表 letters ,列表中只包含小寫英文字母。另給出一個目標字母target,請你尋找在這一有序列表裡比目標字母大的最小字母。
在比較時,字母是依序迴圈出現的。舉個例子:
如果目標字母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"
題解
語言:C++
思路:二分法
class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { int l = 0; int r = letters.size() - 1; if(letters[r] <= target){ return letters[l]; } while(l < r){ int mid = l + r >> 1; if(letters[mid] > target){ r = mid; }else{ l = mid + 1; } } return letters[l] > target ? letters[l] : letters[l+1]; } };