744. Find Smallest Letter Greater Than Target

 
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        // sanity check 
        if(letters[letters.length - 1] <= target ) return letters[0];
        int left = 0;
        int right = letters.length - 1;
        while(left < right){
            int mid = left + (right - left) / 2;
            if(letters[mid] <= target){
                left = mid + 1;
            }else {
                right = mid;
            }
        }
        return letters[left];
    }
}

一開始這個規則沒看到,spa

Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.code

把規則都弄清楚後, 仍是走例子, blog

 

 

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.element

Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.get

Examples:it

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"
相關文章
相關標籤/搜索