744. Find Smallest Letter Greater Than Target

description

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'.

Examples:

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

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

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

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

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

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

Note:

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

Code

  1. 二分法,时间复杂度O(logN),空间复杂度O(1)
    思路
    和459.排序数组中最接近元素思路类似,细节上差别
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        if (letters == null || letters.length == 0) {
            return 'A';
        } 
        
        int index = findIndex(letters, target);
        if (index == 0) {
            return letters[0];
        }
        if (index == letters.length) {
            return letters[0];
        }
        return letters[index];
    }  
    
    private int findIndex(char[] letters, char target) {
        int start = 0;
        int end = letters.length - 1;
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (letters[mid] <= target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        if (letters[start] > target) {
            return start;
        }
        if (letters[end] > target) {
            return end;
        }
        return letters.length;
    }
}
  1. 记录浏览过的字母,时间复杂度O(N),空间复杂度O(1)
    思路
    用 seen[26] 布尔数组存储是否遍历过相应字母,从 target 对应字母开始递增查找,找到的第一个seen[target - 'a']为true对应的字母就是我们要查找的值,如果 target 大于z时还没找到,将 target 置为a , 继续查找
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        boolean[] seen = new boolean[26];
        for (char c: letters)
            seen[c - 'a'] = true;

        while (true) {
            target++;
            if (target > 'z') target = 'a';
            if (seen[target - 'a']) return target;
        }
    }
}
  1. 遍历,时间复杂度O(N),空间复杂度O(1)
    思路
    字母数组是排序的,遍历字母数组,找到大于 target 的字母,遍历到最后还没找到就返回 letters[0]
class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        for (char c: letters)
            if (c > target) return c;
        return letters[0];
    }
}

后两种方法都是暴力解法

你可能感兴趣的:(744. Find Smallest Letter Greater Than Target)