-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindFirstAndLastPositionOfElementInSortedArray.py
55 lines (39 loc) · 1.32 KB
/
FindFirstAndLastPositionOfElementInSortedArray.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
51
52
53
54
55
class Solution:
def getFirstIndexOf(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) - 1
pivot = (end - start) // 2
candidate = -1
while end > start:
if nums[pivot] == target:
candidate = pivot
if nums[pivot] >= target:
end = pivot - 1
else:
start = pivot + 1
pivot = start + (end - start) // 2
if nums[start] == target:
candidate = start
return candidate
def getLastIndexOf(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) - 1
pivot = (end - start) // 2
candidate = -1
while end > start:
if nums[pivot] == target:
candidate = pivot
if nums[pivot] <= target:
start = pivot + 1
else:
end = pivot - 1
pivot = start + (end - start) // 2
if nums[start] == target:
candidate = start
return candidate
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums) < 1:
return [-1, -1]
firstIdx = self.getFirstIndexOf(nums, target)
lastIdx = self.getLastIndexOf(nums, target)
return [firstIdx, lastIdx]