57. LeetCode 744. 寻找比目标字母大的最小字母

2019-02-12  本文已影响10人  月牙眼的楼下小黑

给定一个只包含小写字母的有序数组 letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。

数组里字母的顺序是循环的。举个例子,如果目标字母 target = 'z' 并且有序数组为letters = ['a', 'b'],则答案返回 '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 是一个小写字母。
"""

LeetCode475. 供暖器 解法类似。用二分法寻找插入区间。

class Solution(object):
    def nextGreatestLetter(self, letters, target):
        """
        :type letters: List[str]
        :type target: str
        :rtype: str
        """
        if target >= letters[-1]:
            return letters[0]
        if target < letters[0]:
            return letters[0]
        else:
            low, high = 0, len(letters) - 1
            while(high - low > 1):
                mid = (low + high) // 2
                if letters[mid]<= target:
                    low = mid
                else:
                    high = mid
            return letters[high]
        

暂略。

上一篇 下一篇

猜你喜欢

热点阅读