-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_34.py
More file actions
56 lines (50 loc) · 1.46 KB
/
leetcode_34.py
File metadata and controls
56 lines (50 loc) · 1.46 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
# coding=utf-8
from typing import List
class Solution:
"""
有序数组中查找数字的开始和结束下标
"""
def find_first_and_last_position(self, nums: List[int], target: int) -> List[int]:
"""
Time: O(n), Space: O(1)
:param nums:
:param target:
:return:
"""
if not nums:
return [-1, -1]
start = end = -1
for i in range(0, len(nums)):
if start == -1 and nums[i] == target:
start = i
if nums[i] == target:
end = i
return [start, end]
def binary_search_last_one(self, nums: List[int], target: int) -> int:
"""
:param nums:
:param target:
:return:
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] > target:
high = mid - 1
else:
low = mid + 1
return high
def binary_search_first_and_last_position(self, nums: List[int], target: int) -> List[int]:
"""
Time: O(n), Space: O(1)
:param nums:
:param target:
:return:
"""
if not nums:
return [-1, -1]
end = self.binary_search_last_one(nums, target)
start = self.binary_search_last_one(nums, target - 1) + 1
if 0 <= start <= end < len(nums):
return [start, end]
return [-1, -1]