题解 | #二分查找-I#

二分查找-I

https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b

解题思路

时间复杂度为O(logn),空间复杂度为O(1)。

class Solution:
    def search(self , nums: List[int], target: int) -> int:
        # 注意判断数组为空的情况
        if len(nums) == 0:
            return -1

        left = 0
        right = len(nums)

        while left <= right:  # 注意临界条件,小于等于
            mid = (left+right)//2
            # print(mid, nums[mid])
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        
        return -1

全部评论

相关推荐

野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务