[LeetCode] 744. Find Smallest Letter Greater Than Target_Easy tag: **Binary Search

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:

  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.

思路存ans和看到的最小的char, 如果没有ans, 我们就返回最小的char. O(n)

Code

class Solution:
    def nextGreatestLetter(self, letters, target):
        ans = [None] *2 # [0] 记录ans, [1] 记录最小的letters
        for c in letters:
            if not ans[1] or ord(c) < ord(ans[1]):
                ans[1] = c
            if ord(c) > ord(target) and (not ans[0] or ord(ans[0]) > ord(c)):
                ans[0] = c
        return ans[0] if ans[0] else ans[1]

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9503508.html
今日推荐