-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path34.py
109 lines (93 loc) · 2.97 KB
/
34.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# [ LeetCode ] 34. Find First and Last Position of Element in Sorted Array
def solution(nums: list[int], target: int) -> list[int]:
answer: list[int] = []
is_exist: bool = False
start, end = 0, len(nums) - 1
while start <= end:
middle: int = start + (end - start) // 2
compare: int = nums[middle]
if compare < target:
start = middle + 1
elif compare > target:
end = middle - 1
else:
is_exist = True
end = middle - 1
if is_exist:
answer.append(start)
else:
answer.append(-1)
start, end = 0, len(nums) - 1
while start <= end:
middle: int = start + (end - start) // 2
compare: int = nums[middle]
if compare > target:
end = middle - 1
elif compare < target:
start = middle + 1
else:
is_exist = True
start = middle + 1
if is_exist:
answer.append(end)
else:
answer.append(-1)
return answer
def another_soluion(nums: list[int], target: int) -> list[int]:
def find_index(nums: list[int], target: int, is_from_left: bool) -> int:
start, end = 0, len(nums) - 1
while start <= end:
middle: int = start + (end - start) // 2
compare: int = nums[middle]
if compare > target:
end = middle - 1
elif compare < target:
start = middle + 1
else:
if is_from_left:
if middle == start or nums[middle - 1] < target:
return middle
else:
end = middle - 1
else:
if middle == end or nums[middle + 1] > target:
return middle
else:
start = middle + 1
return -1
left_index: int = find_index(
nums=nums, target=target, is_from_left=True
)
if left_index == -1:
return [-1, -1]
else:
right_index: int = find_index(
nums=nums, target=target, is_from_left=False
)
return [left_index, right_index]
if __name__ == "__main__":
cases: list[dict[str, dict[str, list[int] | int] | list[int]]] = [
{
"input": {
"nums": [5, 7, 7, 8, 8, 10],
"target": 8
},
"output": [3, 4]
},
{
"input": {
"nums": [5, 7, 7, 8, 8, 10],
"target": 6
},
"output": [-1, -1]
},
{
"input": {
"nums": [],
"target": 0
},
"output": [-1, -1]
}
]
for case in cases:
assert case["output"] == solution(**case["input"])