https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/
public char nextGreatestLetter(char[] letters, char target) {
for (char c: letters)
if (c > target) return c;
return letters[0];
}
public char nextGreatestLetter(char[] letters, char target) {
boolean[] seen = new boolean[26];
for (char c: letters)
seen[c - 'a'] = true;
while (true) {
target++;
if (target > 'z') target = 'a';
if (seen[target - 'a']) return 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'
.
public char nextGreatestLetter(char[] letters, char target) {
int lo = 0, hi = letters.length;
while (lo < hi) {
int mi = lo + (hi - lo) / 2;
if (letters[mi] <= target) lo = mi + 1;
else hi = mi;
}
return letters[lo % letters.length];
}
public char nextGreatestLetter(char[] letters, char target) {
for (char c: letters)
if (c > target) return c;
return letters[0];
}
public char nextGreatestLetter(char[] letters, char target) {
boolean[] seen = new boolean[26];
for (char c: letters)
seen[c - 'a'] = true;
while (true) {
target++;
if (target > 'z') target = 'a';
if (seen[target - 'a']) return target;
}
}