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"
[暴力解法]:
時間分析:
空間分析:
[優化後]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
Input: letters = ["c", "f", "j"] target = "k" Output: "c"
結果是最後一位,但是需要返回第一位 結果%n (看余數 不止看倍數)
[思維問題]:
“第一個最大”居然沒看出來是二分查找問題。字母換成index數字後繼續操作啊
[一句話思路]:
[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
“第一個最大”居然沒看出來是二分查找問題。字母換成index數字後繼續操作啊
[復雜度]:Time complexity: O(lgn) Space complexity: O(1)
[英文數據結構或算法,為什麽不用別的數據結構或算法]:
[關鍵模板化代碼]:
九章的不行就用這一套:
while (lo < hi)
lo = mid + 1
//Terminal condition is ‘lo < hi‘, to avoid infinite loop when target is smaller than the first element while (lo < hi) { int mid = lo + (hi - lo) / 2; if (a[mid] > x) hi = mid; else lo = mid + 1; //a[mid] <= x }
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
class Solution { public char nextGreatestLetter(char[] letters, char target) { //ini int n = letters.length; int start = 0, end = n; //bs while (start < end) { int mid = start + (end - start) / 2; if (target < letters[mid]) { end = mid; }else { start = mid + 1; } } //return return letters[start % n]; } }View Code
744. Find Smallest Letter Greater Than Target 查找比目標字母大的最小字母