leetcode34-- Find First and Last Position of Element in Sorted Array

小郑之家~

题目

34. Find First and Last Position of Element in Sorted Array
Medium

1199

64

Favorite

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



解法


class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) == 0:
return [-1, -1]
if len(nums) == 1 and target==nums[0]:
return [0,0]
if len(nums)==1 and target != nums[0]:
return [-1, -1]

start, end = 0, len(nums)-1

flag = -1
while(start+1<end):
mid = start + (end-start)/2

if nums[mid]==target:
flag = mid
break
elif(nums[mid]>target):
end = mid
else:
start = mid

Start, End = -1,-1

if(flag!=-1):
# 向前向后找
temp1 = flag
temp2 = flag
while( nums[temp1] == target):
temp1 -=1
if temp1<0:
break
while(nums[temp2]==target):
temp2 += 1
if temp2>len(nums)-1:
break

Start = temp1+1
End = temp2 -1
return [Start, End]
else:
if(nums[start] == target):
flag = start
temp1 = flag
temp2 = flag
while( nums[temp1] == target):
temp1 -=1
if temp1<0:
break
while(nums[temp2]==target):
temp2 += 1
if temp2>len(nums)-1:
break

Start = temp1+1
End = temp2 -1
return [Start, End]

elif(nums[end]==target):

flag = end
temp1 = flag
temp2 = flag
while( nums[temp1] == target):
temp1 -=1
if temp1 <0:
break
while(nums[temp2]==target):
temp2 += 1
if temp2>len(nums)-1:
break

Start = temp1+1
End = temp2 -1
return [Start, End]
else:
return [-1, -1]




class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto ret = equal_range(nums.begin(), nums.end(), target);
if(ret.first==ret.second){
return {-1,-1};
}
return {ret.first-nums.begin(), ret.second-nums.begin()-1};

}
};