Skip to content

Commit d2544aa

Browse files
committed
元素出现区间(两次二分搜索)
1 parent 7c698f0 commit d2544aa

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

BinarySearch/34_SearchForARange.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/search-for-a-range/description.
6+
题目描述:
7+
8+
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
9+
10+
Your algorithm's runtime complexity must be in the order of O(log n).
11+
12+
If the target is not found in the array, return [-1, -1].
13+
14+
For example,
15+
Given [5, 7, 7, 8, 8, 10] and target value 8,
16+
return [3, 4].
17+
18+
"""
19+
20+
21+
class Solution(object):
22+
def searchRange(self, nums, target):
23+
"""
24+
:type nums: List[int]
25+
:type target: int
26+
:rtype: List[int]
27+
"""
28+
if not nums:
29+
return [-1, -1]
30+
31+
# 两次二分搜索
32+
return [self.searchLeftRange(nums, target), self.searchRightRange(nums, target)]
33+
34+
def searchLeftRange(self, nums, target):
35+
left = 0
36+
right = len(nums) - 1
37+
while left <= right:
38+
mid = left + (right - left) // 2
39+
if nums[mid] == target:
40+
right = mid - 1
41+
elif nums[mid] < target:
42+
left = mid + 1
43+
else:
44+
right = mid - 1
45+
46+
if left < len(nums) and nums[left] == target:
47+
return left
48+
49+
return -1
50+
51+
def searchRightRange(self, nums, target):
52+
left = 0
53+
right = len(nums) - 1
54+
while left <= right:
55+
mid = left + (right - left) // 2
56+
if nums[mid] == target:
57+
left = mid + 1
58+
elif nums[mid] < target:
59+
left = mid + 1
60+
else:
61+
right = mid - 1
62+
63+
if right >= 0 and nums[right] == target:
64+
return right
65+
66+
return -1

0 commit comments

Comments
 (0)