Permalink
Cannot retrieve contributors at this time
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?
LeetCode/find-first-and-last-position-of-element-in-sorted-array
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
62 lines (55 sloc)
1.93 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |