Leetcode 744. Find Smallest Letter Greater Than Target

295 篇文章 2 订阅
150 篇文章 0 订阅
该篇博客介绍了一种使用二分查找算法在已排序的字符数组中找到大于目标字符的最小元素的方法。代码实现中,定义了一个名为`nextGreatestLetter`的函数,通过迭代或递归方式查找目标,并在找不到时返回数组的第一个元素。这个算法适用于有序字符集合的高效搜索。
摘要由CSDN通过智能技术生成

Problem

Given a characters array letters that is sorted in non-decreasing order and a character target, return the smallest character in the array that is larger than target.
Note that the letters wrap around.

  • For example, if target == ‘z’ and letters == [‘a’, ‘b’], the answer is ‘a’.

Algorithm

Binary Search.

Code

class Solution:
    def nextGreatestLetter(self, letters: List[str], target: str) -> str:
        L, R = 0, len(letters)-1
        while L < R:
            Mid = (L + R) // 2
            if letters[Mid] <= target:
                L = Mid + 1
            else: R = Mid
        if letters[R] <= target:
            return letters[0]
        return letters[R]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值