forked from HairuoLiu/Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC35_SearchInsertPosition.java
More file actions
72 lines (67 loc) · 1.54 KB
/
Copy pathLC35_SearchInsertPosition.java
File metadata and controls
72 lines (67 loc) · 1.54 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 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'.
*
* Examples:
* Input:
* letters = ["c", "f", "j"]
* target = "a"
* Output: "c"
*
* Input:
* letters = ["c", "f", "j"]
* target = "c"
* Output: "f"
*
* Input:
* letters = ["c", "f", "j"]
* target = "d"
* Output: "f"
*
* Input:
* letters = ["c", "f", "j"]
* target = "g"
* Output: "j"
*
* Input:
* letters = ["c", "f", "j"]
* target = "j"
* Output: "c"
*
* Input:
* letters = ["c", "f", "j"]
* target = "k"
* Output: "c"
*
* @authorLiu.3502
* @created2018-01-31 下午6:45
*/
public class LC35_SearchInsertPosition{
public static void main(String[] args) {
char[] letter = {'c', 'f', 'j'};
char target = 'k';
char ans = nextGreatestLetter(letter,target);
System.out.println(ans);
}
public static char nextGreatestLetter(char[] letters, char target) {
int left = 0, right = letters.length - 1;
//sanity cheak
if(right <= 0){
return ' ';
}
while (left <= right){
int mid = left + (right - left) / 2;
if(letters[mid] <= target){
left = mid + 1;
}else if(letters[mid] > target ){
right = mid-1;
}
}
if(left == letters.length ){
return letters[0];
}
return letters[left];
}
}