二分法。需要注意左闭右开区间,l+1,r不需要-1,另外因为要找的是大于target的字母,所以 if 判断条件<=target
循环条件是l<r或者 l!=r 均可
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
const int n = letters.size();
int l = 0;
int r = n;
while(l!=r) {
int mid = (l+r)/2;
if(letters[mid]<=target) {
l = mid+1;
}
else {
r = mid;
}
}
return letters[l%n];
}
};