forked from python-geeks/Leetcode-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirstAndLastPositionOfElementInSortedArray.py
More file actions
74 lines (54 loc) · 2.02 KB
/
Copy pathfirstAndLastPositionOfElementInSortedArray.py
File metadata and controls
74 lines (54 loc) · 2.02 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution:
def searchRange(self, arr, target):
n = len(arr)
# find leftIndex
leftIndex = -1
# start is the first index of the array
start = 0
# end is the last index of the array
end = n - 1
while(start <= end):
# mid = (start+end)//2
# (start + end) might exceed the range of integers
# better way to do this
mid = start + (end - start) // 2
# if target element is equal to the middle element
if arr[mid] == target:
# potential answer is found
leftIndex = mid
# continue searching in left of mid
end = mid - 1
# target element is less than middle element
# search in the left
elif target < arr[mid]:
end = mid - 1
# target element is greater than middle element
# search in the right
elif target > arr[mid]:
start = mid + 1
# find rightIndex
rightIndex = -1
# start is the first index of the array
start = 0
# end is the last index of the array
end = n - 1
while(start <= end):
# mid = (start+end)//2
# (start + end) might exceed the range of integers
# better way to do this
mid = start + (end - start) // 2
# if target element is equal to the middle element
if arr[mid] == target:
# potential answer is found
rightIndex = mid
# continue searching in right of mid
start = mid + 1
# target element is less than middle element
# search in the left
elif target < arr[mid]:
end = mid - 1
# target element is greater than middle element
# search in the right
elif target > arr[mid]:
start = mid + 1
return [leftIndex, rightIndex]