二分查找

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)
全部评论

相关推荐

11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务