Find Smallest Letter Greater Than Target


  • 0

    Click here to see the full article post


  • 0
    R

    class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
    int index = binarySearch(letters, 0, letters.length-1, target);
    return index == -1 ? letters[0] : letters[index];
    }

    private int binarySearch(char[] letters, int low, int high, char target) {
        if (low > high)
            return -1;
         
        if (high == low && letters[low] > target)
            return low;
        
        int mid = (low + high) >>> 1;
    
        if (letters[mid] <= target) {
            return binarySearch(letters, mid+1, high, target);
        } else {
            int index = binarySearch(letters, low, mid-1, target);
            return index == -1 ? mid : index;
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.