leetcode:(69)Find Smallest Letter Greater Than Target(java)

题目:

    

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"

解题思路:

   利用二分查找。具体思路及代码如下:

package Leetcode_Github;

public class BinarySearch_NextGreaterLetters_744_1113 {
    public char NextGreaterLetter(char[] letters, char target) {
        int l = 0;
        int h = letters.length - 1;
        while (l <= h) {
            int mid = l + (h - l) / 2;
            if (letters[mid] > target) {
                h = mid - 1;
            } else
                l = mid + 1;
        }
        return l < letters.length ? letters[l] : letters[0];
    }
}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/84025749
今日推荐