-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path034_searchForARange.py
50 lines (44 loc) · 1.34 KB
/
034_searchForARange.py
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
40
41
42
43
44
45
46
47
48
49
50
# O(n) solution
# class Solution:
# def searchRange(self, nums, target):
# """
# :type nums: List[int]
# :type target: int
# :rtype: List[int]
# """
# if (not nums):
# return [-1, -1]
# try:
# start = nums.index(target)
# if (start == -1):
# return [-1, -1]
# n = len(nums)
# for i in range(start+1, n):
# if (nums[i] != target):
# end = i - 1
# return [start, end]
# end = n - 1
# return [start, end]
# except:
# return [-1, -1]
# O(log n) solution
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def findPosition(findLow):
low = 0
high = n
while(low < high):
mid = (low+high)//2
if (nums[mid] == target and findLow) or (nums[mid] > target):
high = mid
else:
low = mid + 1
return low
n = len(nums)
if n == 0:
return [-1,-1]
leftPos = findPosition(True)
if (leftPos == n) or (nums[leftPos] != target):
return [-1,-1]
rightPos = findPosition(False)-1
return [leftPos, rightPos]