-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSearchRange.py
More file actions
39 lines (35 loc) · 950 Bytes
/
SearchRange.py
File metadata and controls
39 lines (35 loc) · 950 Bytes
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
34
35
36
37
38
39
# 034. Find First and Last Position of Element in Sorted Array
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = [-1, -1]
if not nums:
return result
index = -1
l = 0
h = len(nums) - 1
while l <= h:
m = int((l + h)/2)
if nums[m] == target:
index = m
break
elif nums[m] < target:
l = m + 1
else:
h = m - 1
if index == -1:
return result
else:
ls = index
while ls >= 0 and nums[ls] == target:
result[0] = ls
ls -= 1
rs = index
while rs < len(nums) and nums[rs] == target:
result[1] = rs
rs += 1
return result