欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Find Smallest Letter Greater Than Target

程序员文章站 2024-03-07 13:00:33
...

Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.

Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.

Note:

  1. letters has a length in range [2, 10000].
  2. letters consists of lowercase letters, and contains at least 2 unique letters.
  3. target is a lowercase letter.

LeetCode744题,找到比目标字符大的第一个字符。此题Accepted代码如下:

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        char a = 0;
        for (int i = 0; i < letters.length; i++) {
            if (letters[i] > target) {
                a = letters[i];
                break;
            } else {
                a = letters[0];
            }
        }
        return a;
    }
}
此题逻辑不复杂,但是由于我开始第3行只写了char c,运行的时候总是报未初始化。而后我又尝试了char c = '' char c = null,发现均不可行。后仔细思考,char不是引用类型,不可能和null有关系,写成以上或char a = 'a'均可。