leetcode二分查找之大于给定元素的最小元素744. Find Smallest Letter Greater Than Target (Easy)

Input:
letters = ["c", "f", "j"]
target = "d"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "k"
Output: "c"

题目描述:给定一个有序的字符数组 letters 和一个字符 target,要求找出 letters 中大于 target 的最小字符,如果找不到就返回第 1 个字符。

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int n = letters.length;
        int l = 0, h = n - 1;
        while(l<=h)
        {
            int m = l + (h-1)/2;
            if(letters[m] <= target)
            {
                l = m + 1;
            }else{
                h = m - 1;
            }
        } 
        return l < n ? letters[l]:letters[0];
    }
}

 

posted on 2020-05-20 21:37  Hebye  阅读(155)  评论(0编辑  收藏  举报

导航