46.leetcode34_search_for_a_range

1.题目描述

Given an array of integers 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

2.解题思路

双指针分别从首尾向中间移动

Python代码(47ms)

 1 class Solution(object):
 2     def searchRange(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         index1=0
 9         index2=0
10         l=len(nums)-1
11         i=0
12         while i<l+1:
13             if nums[i]<target:
14                 i+=1
15             else:
16                 index1=i
17                 break
18         while l>=0:
19             if nums[l]>target:
20                 l-=1
21             else:
22                 index2=l
23                 break
24         if target not in nums:
25             return [-1,-1]
26         return [index1,index2]

 

转载于:https://www.cnblogs.com/19991201xiao/p/8490971.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值