34. Find First and Last Position of Element in Sorted Array

34. Find First and Last Position of Element in Sorted Array

Description

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.


Exceptions

There will be a chance that the target cannot be found in the array.

Python Code

The array is sorted and we need a O(logn) solution. So we can use the binary search template to find the first target and then find the last target.The only difference is:
find first: if nums[mid] == target: end = mid and check if nums[start] == target in the end.
find last: if nums[mid] == target: start = mid and check if nums[end] == target in the end.

    def searchRange(self, nums: List[int], target: int) -> List[int]:
        if not nums:
            return [-1, -1]
        start, end = 0, len(nums) - 1
        res = [-1, -1]
        
        #find first
        '''
        remember start < end - 1 to avoid infinite loop
        '''
        while start < end - 1:
            mid = (start + end) // 2
            '''
            mid need to be included as well
            '''
            if nums[mid] >= target:
                end = mid
            else:
                start = mid
        '''
        check start first since we are finding the first target position
        '''
        if nums[start] == target:
            res[0] = start
        elif nums[end] == target:
            res[0] = end
            
        # find last  
        start, end = 0, len(nums) - 1 
        while start < end - 1:
            mid = (start + end) // 2
            if nums[mid] <= target:
                start = mid
            else:
                end = mid
        if nums[end] == target:
            res[1] = end
        elif nums[start] == target:
            res[1] = start
            
        return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值