-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstandLastposition.py
More file actions
33 lines (31 loc) · 1.08 KB
/
FirstandLastposition.py
File metadata and controls
33 lines (31 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution(object):
def searchRange(self, nums, target):
def binSearchleft(nums, min, max, target):
while min < max:
mid = (max + min) // 2
if target > nums[mid]:
min = mid + 1
elif target < nums[mid]:
max = mid
else:
max = mid
if min < len(nums) and nums[min] == target:
return min
else:
return -1
def binSearchright(nums, min, max, target):
while min < max:
mid = (max + min) // 2
if target > nums[mid]:
min = mid + 1
elif target < nums[mid]:
max = mid
else:
min = mid + 1
if max > 0 and nums[max - 1] == target:
return max - 1
else:
return -1
left = binSearchleft(nums, 0, len(nums), target)
right = binSearchright(nums, 0, len(nums), target)
return [left, right]