744. Find Smallest Letter Greater Than Target

744. Find Smallest Letter Greater Than Target

题目描述

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:
letters has a length in range [2, 10000].
letters consists of lowercase letters, and contains at least 2 unique letters.
target is a lowercase letter.

题目大意

letters 是有序数组,找到 letters 中第一个大于 target 的值,如果不存在,则返回最小值。

解题思路

二分查找。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character {
var l = 0, r = letters.count - 1
while l < r - 1 {
let m = l + (r - l) / 2
if letters[m] <= target {
l = m + 1
}else {
r = m
}
}
if letters[l] > target { return letters[l] }
if letters[r] > target { return letters[r] }
return letters[0]
}
}
0%