原题地址(简单)

方法1—二分查找

经典的二分查找题目

代码

  1. class Solution:
  2. def nextGreatestLetter(self, letters: List[str], target: str) -> str:
  3. n = len(letters)
  4. low, high = 0, n - 1
  5. while low <= high:
  6. mid = low + (high - low) // 2
  7. if letters[mid] > target:
  8. high = mid - 1
  9. else: # letters[mid] < target
  10. low = mid + 1
  11. return letters[low % n]

时空复杂度

时间复杂度 O(logN)
空间复杂度 O(1)