744 Find Smallest Letter Greater Than Target

1. Question

Given a list of sorted charactersletterscontaining only lowercase letters, and given a target lettertarget, find the smallest element in the list that is larger than the given target.

Letters also wrap around. For example, if the target istarget = 'z'andletters = ['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"

Note:

  1. lettershas a length in range[2, 10000].

  2. lettersconsists of lowercase letters, and contains at least 2 unique letters.

  3. targetis a lowercase letter.

2. Implementation

(1) Binary Search

思路: 非常典型的二分查找 找左边界,思路和search insert position是一样的,其中注意题目要求letters是可以wrap around的 (也就是如果target在数组的插入点是在数组末端的时候,则数组的第一个字母为所求解)

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int start = 0, end = letters.length - 1, mid = 0;

        while (start + 1 < end) {
            mid = start + (end - start) / 2;
            if (letters[mid] <= target) {
                start = mid + 1;
            }
            else {
                end = mid;
            }
        }

        if (letters[start] > target) {
            return letters[start];
        }
        else if (letters[end] > target) {
            return letters[end];
        }
        else {
            return letters[0];
        }
    }
}

3. Time & Space Complexity

Binary Search: 时间复杂度O(logn), 空间复杂度O(1)

Last updated