Greater than the smallest element of the given element
744. Find Smallest Letter Greater Than Target (Easy)
Input:
letters = ["c", "f", "j"]
target = "d"
Output: "f"
Input:
letters = ["c", "f", "j"]
target = "k"
Output: "c"
Subject description:
Given an ordered array of characters and a character target letters, asked to identify letters larger than the smallest character in the target, if not found returns the first character.
Analysis of ideas:
Dichotomy to find.
Code:
public char nextGreatestLetter(char []letters,char target){
if(letters==null||letters.length==0)
return null;
int len=letters.length;
int l=0,h=n-1;
while(l<=h){
int mid=l+(h-l)/2;
if(letters[mid]<=target){
l=mid+1;
}else{
h=mid-1;
}
}
return l<len?letters[l]:letters[0];
}