题目内容
https://leetcode-cn.com/problems/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]
.
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]
给定一个按照升序排列的整数数组 nums
,和一个目标值 target
。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]
。
题目思路
首先要确定target是否在数组中。接下来可以先确定第一个出现的位置。然后在第一个位置的基础上向后查找,直到找出第一个不一样的加入。如果一直都一样到底部,就把最后一个位置添加进去。
第二种方法,我们考虑使用左右双指针的方法搜寻起始和终止位置。
程序代码
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if nums.count(target)<1:
return [-1,-1]
else:
left,right=0,len(nums)-1
while left<=right:
if nums[left]!=target:
left+=1
if nums[right]!=target:
right-=1
if nums[left]==target and nums[right]==target:
break
return [left,right]