二分查找

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        #查找nums数组中target出现的下标位置,若target不在nums中,返回-1
        def searchN(nums, target):
            left, right = 0, len(nums)-1
            while left<=right:
                mid = (left+right)//2
                if nums[mid]==target:
                    return mid
                elif nums[mid]>target:
                    right = mid-1
                else:
                    left = mid+1
            return -1
        #nums数组中可能存在重复数组,若target在nums中,返回第一次出现的位置,否则返回-1
        def searchFirstN(nums, target):
            left, right = 0, len(nums)-1
            while left<=right:
                mid = (left+right)//2
                if nums[mid]==target:
                    if mid==0 or nums[mid-1]!=target:
                        return mid
                    else:
                        right = mid-1
                elif nums[mid]>target:
                    right = mid-1
                else:
                    left =mid+1
            return -1
        #nums数组中可能存在重复数组,若target在nums中,返回最后一次出现的位置,否则返回-1
        def searchLastN(nums, target):
            left, right = 0, len(nums)-1
            while left<=right:
                mid = (left+right)//2
                if nums[mid]==target:
                    if mid==len(nums)-1 or nums[mid+1]!=target:
                        return mid
                    else:
                        left = mid+1
                elif nums[mid]>target:
                    right = mid-1
                else:
                    left =mid+1
            return -1
        #查找nums数组中第一个大于等于target的下标位置.否则返回-1(表示数组中的数均小于target)
        def searchFirstUpperN(nums, target):
            left, right = 0, len(nums)-1
            while left<=right:
                mid = (left+right)//2
                if nums[mid]>=target:
                    if mid==0 or nums[mid-1]<target:
                        return mid
                    #缩小边界,往左寻找
                    right = mid-1
                else:
                    left = mid+1
            return -1
        #查找nums数组中最后一个小于等于target的下标位置,否则返回-1(nums数组中数字均大于target)
        def searchLastLessN(nums, target):
            left, right = 0, len(nums)-1
            while left<=right:
                mid = (left+right)//2
                if nums[mid]<=target:
                    if mid==len(nums)-1 or nums[mid+1]>target:
                        return mid
                    left = mid+1
                else:
                    right = mid-1
            return -1
        return searchN(nums, target)
全部评论

相关推荐

AI牛可乐:哇,听起来你遇到了什么挑战呢!🐮牛可乐在这里,虽然小,但是勇敢又聪明,想听听你的具体情况哦!如果你愿意的话,可以点击我的头像给我私信,我们可以一起想办法应对挑战,好不好呀?🌟🎉
点赞 评论 收藏
分享
11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务