1. 程式人生 > 實用技巧 >744. Find Smallest Letter Greater Than Target

744. Find Smallest Letter Greater Than Target

問題:

給定一個升序字元陣列。

求比給定target字元大的,最小的字元。(假設給定字元陣列是迴圈的,即第一個字元>最後一個字元)

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.

  

解法:二分查詢(Binary Search)

在給定字元陣列letters中,找到第一個>target字元的字元。

⚠️ 注意:(字元陣列是迴圈:)若未找到,則返回letters[0]

程式碼參考:

 1 class Solution {
 2 public:
 3     char nextGreatestLetter(vector<char>& letters, char target) {
 4         int l = 0, r = letters.size();
 5         while(l<r) {
 6             int
m = l+(r-l)/2; 7 if(letters[m]>target) {//找到第一個>target 8 r = m; 9 } else { 10 l = m+1; 11 } 12 } 13 return (l==letters.size())?letters[0]:letters[l]; 14 } 15 };