题目链接:
力扣https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/
【分析】二分查找第一个大于target的元素,需要注意当target<mid的才缩短左区间,并且返回left
class Solution {
public int binarySearch(char[] letters, char target){
int left = 0, right = letters.length - 1, mid;
while(left <= right){
mid = (left + right) >>> 1;
if(target < letters[mid]) right = mid - 1;
else left = mid + 1;
}
return left;
}
public char nextGreatestLetter(char[] letters, char target) {
int idx = binarySearch(letters, target);
return letters[idx % letters.length];
}
}