# [LeetCode] 744. Find Smallest Letter Greater Than Target

2021-01-14 03:32:03  阅读：14  来源： 互联网

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"```

Note:

1. `letters` has a length in range `[2, 10000]`.
2. `letters` consists of lowercase letters, and contains at least 2 unique letters.
3. `target` is a lowercase letter.

Java实现

``` 1 class Solution {
2     public char nextGreatestLetter(char[] letters, char target) {
3         int len = letters.length;
4         // corner case
5         if (target >= letters[len - 1]) {
6             return letters[0];
7         }
8
9         // normal case
10         int start = 0;
11         int end = len - 1;
12         while (start + 1 < end) {
13             int mid = start + (end - start) / 2;
14             if (letters[mid] - target > 0) {
15                 end = mid;
16             } else {
17                 start = mid;
18             }
19         }
20         if (letters[start] > target) {
21             return letters[start];
22         } else {
23             return letters[end];
24         }
25     }
26 }```