Leetcode744 looking larger than the minimum target letter alphabet

topic

Given that contains only lowercase letters ordered array of letters and a target letter target, find an ordered array which is larger than the minimum target letter alphabet.

In alphabetical order of the array is the loop. For example, if the target letter target = 'z' and ordered array of letters = [ 'a', 'b'], returns the answer '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"

answer

The title uses a binary search to solve the conversion problem to find to find half of the left margin. The target value for the left margin again added in the original array binary search, is equivalent to solving the smallest element is greater than the given element.

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

 

Guess you like

Origin www.cnblogs.com/jianglinliu/p/11809507.html