From ee40e18f4d653541dd9ec02fc7fa05c4a4955f61 Mon Sep 17 00:00:00 2001 From: Valentyn Kolesnikov Date: Sat, 30 Apr 2022 18:55:04 +0300 Subject: [PATCH] Improved task 744. --- .../Solution.java | 29 ++++++++----------- .../SolutionTest.java | 6 ++++ 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/src/main/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/Solution.java b/src/main/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/Solution.java index ccd8b3ef1..b348c4d86 100644 --- a/src/main/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/Solution.java +++ b/src/main/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/Solution.java @@ -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]; } } diff --git a/src/test/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/SolutionTest.java b/src/test/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/SolutionTest.java index 995942855..7edf8645e 100644 --- a/src/test/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/SolutionTest.java +++ b/src/test/java/g0701_0800/s0744_find_smallest_letter_greater_than_target/SolutionTest.java @@ -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')); + } }