美文网首页
LeetCode---Find first and last p

LeetCode---Find first and last p

作者: LuDon | 来源:发表于2019-04-18 14:19 被阅读0次

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Solution1:

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # 找左边界
        def left_bound(nums, target):
            left, right = 0, len(nums)
            while(left < right):
                mid = left + (right - left)/2
                if nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid
            return left
        # 找右边界
        def right_bound(nums, target):
            left, right = 0, len(nums)
            while(left < right):
                mid = left + (right - left)/2
                if nums[mid] <= target:
                    left = mid + 1
                else:
                    right = mid
            return right
        
        
        left = left_bound(nums, target)
        right = right_bound(nums, target)
        if left == right:
            return [-1, -1]
        else:
            return [left, right-1]

Solution2:

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        left = bisect.bisect_left(nums, target)
        right = bisect.bisect_right(nums, target)
        if left == right:
            return [-1, -1]
        return [left, right - 1]

相关文章

网友评论

      本文标题:LeetCode---Find first and last p

      本文链接:https://www.haomeiwen.com/subject/snzzwqtx.html