输入:
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"
class Solution {
public char nextGreatestLetter(char[] letters, char target) {
// 记录某个字母是否存在
boolean[] exist = new boolean[26];
for (char c : letters) {
exist[c - 'a'] = true;
}
while (true) {
// 记得++,要找的是target之后的字符
target++;
// 如果越界了就回到最初的起点
if (target > 'z')
target = 'a';
if (exist[target - 'a'])
return target;
}
}
}
class Solution {
fun nextGreatestLetter(letters: CharArray, target: Char): Char {
var target = target
// 记录某个字母是否存在
val exist = BooleanArray(26)
for (c in letters) {
exist[c - 'a'] = true
}
while (true) {
// 记得++,要找的是target之后的字符
target++
// 如果越界了就回到最初的起点
if (target > 'z')
target = 'a'
if (exist[target - 'a'])
return target
}
}
}
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)
left = mid + 1;
else
right = mid;
}
// 如果越界了就取模
return letters[left % letters.length];
}
}
class Solution {
fun nextGreatestLetter(letters: CharArray, target: Char): Char {
var left = 0
var right = letters.size
while (left < right) {
val mid = left + (right - left) / 2
if (letters[mid] <= target)
left = mid + 1
else
right = mid
}
// 如果越界了就取模
return letters[left % letters.size]
}
}