-
Notifications
You must be signed in to change notification settings - Fork 43
/
search-for-a-range.py
75 lines (70 loc) · 2.48 KB
/
search-for-a-range.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
# V0
# V1
# https://siddontang.gitbooks.io/leetcode-solution/content/array/search_for_a_range.html
# https://blog.csdn.net/qqxx6661/article/details/77943936
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, A, target):
left = 0; right = len(A) - 1
while left <= right:
mid = (left + right) / 2
if A[mid] > target:
right = mid - 1
elif A[mid] < target:
left = mid + 1
else:
list = [0, 0]
if A[left] == target: list[0] = left
if A[right] == target: list[1] = right
for i in range(mid, right+1):
if A[i] != target: list[1] = i - 1; break
for i in range(mid, left-1, -1):
if A[i] != target: list[0] = i + 1; break
return list
return [-1, -1]
# V2
# Time: O(logn)
# Space: O(1)
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Find the first idx where nums[idx] >= target
left = self.binarySearch(lambda x, y: x >= y, nums, target)
if left >= len(nums) or nums[left] != target:
return [-1, -1]
# Find the first idx where nums[idx] > target
right = self.binarySearch(lambda x, y: x > y, nums, target)
return [left, right - 1]
def binarySearch(self, compare, nums, target):
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid + 1
return left
def binarySearch2(self, compare, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid - 1
else:
left = mid + 1
return left
def binarySearch3(self, compare, nums, target):
left, right = -1, len(nums)
while left + 1 < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid
return left if left != -1 and compare(nums[left], target) else right