-
Notifications
You must be signed in to change notification settings - Fork 6
/
744. Find Smallest Letter Greater Than Target.java
60 lines (46 loc) · 1.36 KB
/
744. Find Smallest Letter Greater Than Target.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.
For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.
Example 1:
Input: letters = ["c","f","j"], target = "a"
Output: "c"
Example 2:
Input: letters = ["c","f","j"], target = "c"
Output: "f"
Example 3:
Input: letters = ["c","f","j"], target = "d"
Output: "f"
Example 4:
Input: letters = ["c","f","j"], target = "g"
Output: "j"
Example 5:
Input: letters = ["c","f","j"], target = "j"
Output: "c"
Constraints:
2 <= letters.length <= 104
letters[i] is a lowercase English letter.
letters is sorted in non-decreasing order.
letters contains at least two different characters.
target is a lowercase English letter.
*/
class Solution {
public char nextGreatestLetter(char[] arr, char target) {
int start = 0;
int end = arr.length - 1;
while (start <= end){
int mid = start + (end - start) / 2;
if(arr[mid] > target){
end = mid-1;
}else {
start = mid + 1;
}
}
if(start == arr.length){
return arr[0];
}
return arr[start];
//or we can do by this way also
// return arr[start % arr.length];
}
}