Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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]
My code:
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index1,index2=self.find_target(nums,0,len(nums)-1,target)
return [index1,index2]
def find_target(self,nums,i,j,target):
if i>j:
return [-1,-1]
if j-i<=1:
if nums[j]==target and nums[i]==target:
return [i,j]
elif nums[j]==target:
return [j,j]
elif nums[i]==target:
return [i,i]
return [-1,-1]
medium_index=int((i+j)/2)
medium=nums[medium_index]
print('i %d j %d medium %d'%(i,j,medium))
if medium==target:
start=medium_index
while medium==target:
medium_index+=1
if medium_index>=len(nums):
break
medium=nums[medium_index]
medium=nums[start]
while medium==target:
print('start %d medium_index %d medium %d'%(start+1,medium_index-1,medium))
start-=1
if start<0:
break
medium=nums[start]
return [start+1,medium_index-1]
if medium<target:
return self.find_target(nums,medium_index,j,target)
if medium>target:
return self.find_target(nums,i,medium_index,target)
return [-1,-1]
Solution:
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/