Skip to content

Commit

Permalink
Improved task 744.
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev authored Apr 30, 2022
1 parent d40e5e2 commit ee40e18
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -1,29 +1,24 @@
package g0701_0800.s0744_find_smallest_letter_greater_than_target;

// #Easy #Array #Binary_Search #Binary_Search_I_Day_4
// #2022_03_25_Time_0_ms_(100.00%)_Space_42.5_MB_(91.35%)
// #2022_04_30_Time_0_ms_(100.00%)_Space_47.4_MB_(68.35%)

public class Solution {
public char nextGreatestLetter(char[] letters, char target) {
if (letters[0] > target) {
return letters[0];
int start = 0;
int end = letters.length - 1;
// If target is greater than last element return first element of the array.
if (letters[letters.length - 1] <= target) {
return letters[start];
}
int left = 0;
int right = letters.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (letters[mid] > target) {
while (letters[mid] > target) {
mid--;
}
return letters[++mid];
while (start < end) {
int mid = start + (end - start) / 2;
if (letters[mid] <= target) {
start = mid + 1;
} else {
left = mid + 1;
end = mid;
}
}
if (right < letters.length && letters[right] > target) {
return letters[right];
}
return letters[0];
return letters[start];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,10 @@ void nextGreatestLetter3() {
assertThat(
new Solution().nextGreatestLetter(new char[] {'c', 'f', 'j'}, 'd'), equalTo('f'));
}

@Test
void nextGreatestLetter4() {
assertThat(
new Solution().nextGreatestLetter(new char[] {'c', 'f', 'j'}, 'k'), equalTo('c'));
}
}

0 comments on commit ee40e18

Please sign in to comment.