【Leetcode】034 Find First and Last Position of Element in Sorted Array


题目描述

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].

例子

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

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

Input: nums = [1], target = 1
Output: [0,0]

Input: nums = [1,3], target = 3
Output: [1,1]

题目含义是指

  • 存在两个及两个以上的数等于target,那么返回第一个和第最后一个的索引[first_index,last_index].
  • 只有一个数等于target,那返回时返回这个索引两次[index,index].
  • 不存在等于target的元素,则返回[-1,-1]
2019-06-10 linear search
        for i in range(len(nums)):
            if nums[i]==target:
                left = i
                break
        else:	#如果找不到这样的值,则直接返回`[-1,-1]`
            return [-1,-1]
        for j in range(len(nums)-1,-1,-1):
            if nums[j] == target:
                right = j
                break
        print([left,right])
        return [left,right]

Runtime: 68 ms, faster than 75.70% of Python online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 13.4 MB, less than 5.09% of Python online submissions for Find First and Last Position of Element in Sorted Array.

binary search

        def find_right_index(nums,left,right,target):
            while(left<=right):
                mid = (left+right)//2
                if nums[mid]>target:
                    right = mid - 1
                else:
                    left = mid + 1
            return right

        def find_left_index(nums,left,right,target):
            while(left<=right):
                mid = (left+right)//2
                if nums[mid]<target:
                    left = mid + 1
                else:
                    right = mid - 1
            # print(left)
            return left
        res = [-1,-1]
        left, right = 0, len(nums) - 1
        rightmost = find_right_index(nums, left, right, target)
        if (rightmost<0 or nums[rightmost]!=target):
            #print(res)
            return res
        res[0] = find_left_index(nums,left,right,target)
        res[1] = rightmost
        #print(res)
        return res
结果分析

Runtime: 64 ms, faster than 79.51% of Python online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 13.1 MB, less than 38.73% of Python online submissions for Find First and Last Position of Element in Sorted Array.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值