Likou 744. Find the smallest letter larger than the target letter (binary search for the smallest number larger than a number)

744. Find the smallest letter larger than the target letter

Give you a sorted list of letters, the list contains only lowercase English letters. Another target letter is given. Please find the smallest letter that is larger than the target letter in this ordered list.

In the comparison, the letters appear in a cycle. for example:

If the target letter target ='z' and the character list is letters = ['a','b'], the answer returns'a'

示例:

输入:
letters = ["c", "f", "j"]
target = "a"
输出: "c"

输入:
letters = ["c", "f", "j"]
target = "c"
输出: "f"

输入:
letters = ["c", "f", "j"]
target = "d"
输出: "f"

输入:
letters = ["c", "f", "j"]
target = "g"
输出: "j"

输入:
letters = ["c", "f", "j"]
target = "j"
输出: "c"

输入:
letters = ["c", "f", "j"]
target = "k"
输出: "c"
 

提示:

letters长度范围在[2, 10000]区间内。
letters 仅由小写字母组成,最少包含两个不同的字母。
目标字母target 是一个小写字母。

answer:

As we all know, binary search can greatly improve the speed when traversing and searching an ordered array.
So this question can use binary search.
But to make it clear that we are looking for the smallest letter larger than the target letter .
So pay attention to searching when searching binary search

Code:

char nextGreatestLetter(char* letters, int lettersSize, char target){
    
    
    int left = 0;
    int right = lettersSize-1;
    int mid;
    if(target>=letters[lettersSize-1])
    {
    
    
        return letters[0];
    }
    while(left<right)//所以退出循环的时候为left=right
    {
    
    
        mid = left+(right-left)/2;//mid要在里面定义
        if(letters[mid]>target)//此为符合题意,所以mid要保留
        {
    
    
            right = mid;//保留
        }
        else if(letters[mid]<=target)//此不符合
        {
    
    
            left = mid+1;//所以mid直接去除即可
        }
    }
    return letters[left]; //最后我们要得到的目标值在left-right里,又因二者相等,所以输出任何一个即可
}

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/115037039