forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindSmallestLetterGreaterThanTarget.java
More file actions
43 lines (36 loc) · 1013 Bytes
/
FindSmallestLetterGreaterThanTarget.java
File metadata and controls
43 lines (36 loc) · 1013 Bytes
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
package binary_search;
/**
* Description: https://leetcode.com/problems/find-smallest-letter-greater-than-target
* Difficulty: Easy
*/
public class FindSmallestLetterGreaterThanTarget {
/**
* Time complexity: O(nlog n)
* Space complexity: O(1)
*/
public char nextGreatestLetterViaBinarySearch(char[] letters, char target) {
int left = 0;
int right = letters.length - 1;
int result = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (letters[mid] > target) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return letters[result];
}
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public char nextGreatestLetterViaBruteForce(char[] letters, char target) {
for (char c : letters) {
if (c > target) return c;
}
return letters[0];
}
}