LeetCode二分查找:寻找比目标字母大的最小字母
- 如果评论区没有及时回复,欢迎来公众号:ByteCode 咨询
- 公众号:ByteCode。致力于分享最新技术原创文章,涉及 Kotlin、Jetpack、算法、译文、系统源码相关的文章
题目来源于 LeetCode 上第 744 号(Find Smallest Letter Greater Than Target)问题:寻找比目标字母大的最小字母。题目难度为 Easy。
英文地址:https://leetcode.com/problems/find-smallest-letter-greater-than-target/
中文地址:https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/
题目描述
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: |
二分查找
从题意分析从有序列表中找比目标字母大的最小字母得知,这题应该使用二分查找,因为二分查找的时间复杂度 O(logn)
但是这题目有个坑,就是题意给的不准确,笔者也提交几次才通过,总结规律如下:
- 当 target < letters[0] 时,即 letters[0] 是比目标字母大的最小字母,返回 letters[0]
- 当 target >= letters[height -1], 即返回 letters[0]
Java 实现
class Solution { |
Koltin 实现
class Solution { |
- 本文作者:hi-dhl
- 本文标题:LeetCode二分查找:寻找比目标字母大的最小字母
- 本文链接:https://hi-dhl.com/backup/LeetCode/binary-search/03-find-letter.html
- 版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 hi-dhl