Find First and Last Position of Element in Sorted Array

Posted wenqinchao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find First and Last Position of Element in Sorted Array相关的知识,希望对你有一定的参考价值。

问题:给定一个有序数组和一个目标值,输出目标值在数组中的起始位置和终止位置,如果目标值不在数组中,则输出[-1,-1]

示例:

输入:nums = [1,2,3,5,5,7] target = 5

输出:[3,4]

输入:nums = [1,5,8,9] target = 7

输出:[-1,-1]

解决思路:二分查找直到找到第一个目标值,再对目标值左右进行二分查找

Python代码:   

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = 0
        r = len(nums)-1
        while l <= r :
            mid = (l+r)//2
            if nums[mid] > target:
                r = mid - 1
            elif nums[mid] < target:
                l = mid + 1
            else:
                first,last = mid,mid
                while l <= first:
                    fm = (first+l) // 2
                    if nums[fm] < target:
                        l = fm + 1
                    else:
                        first = fm -1
                while r >= last:
                    rm = (last+r) // 2
                    if nums[rm] > target:
                        r = rm - 1
                    else:
                        last = rm + 1
                return [first+1,last-1]
        return [-1,-1]

 

以上是关于Find First and Last Position of Element in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

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

Find First and Last Position of Element in Sorted Array

[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array

[leetcode][34] Find First and Last Position of Element in Sorted Array

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

LeetCode找元素Find First and Last Position of Element in Sorted Array