Find the smallest letter larger than the target letter

5. Find the smallest letter larger than the target letter

5.1. Requirements for the title

​ gives you a sorted list of letters, containing only lowercase English letters. In addition, given a target letter target, please find the smallest letter in this ordered list that is larger than the target letter. When comparing, the letters appear sequentially and cyclically.

举个例子:
如果目标字母 target = 'z' 并且字符列表为 letters = ['a', 'b'],则答案返回 'a'

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

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

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

提示:
2 <= letters.length <= 104
letters[i] 是一个小写字母
letters 按非递减顺序排序
letters 最少包含两个不同的字母
target 是一个小写字母

Source: LeetCode
Link: https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target

5.2. Problem solving ideas

​ Use linear search to compare the characters in the character list with the target letters one by one. If the comparison is found, just jump out of the loop and output.

5.3. Algorithms

class Solution {
    
    
    public char nextGreatestLetter(char[] letters, char target) {
    
    
        char letter = letters[0];
        for(int i = 0;i < letters.length;i++){
    
    
            if(target < letters[i]){
    
    
                letter = letters[i];
                break;
            }
        }
        return letter;
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124051279