Skip to content

Commit d4b1934

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 19.1 MB (7.21%)
1 parent b21dd7e commit d4b1934

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p>
2+
3+
<p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p>
4+
5+
<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8
10+
<strong>Output:</strong> [3,4]
11+
</pre><p><strong class="example">Example 2:</strong></p>
12+
<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6
13+
<strong>Output:</strong> [-1,-1]
14+
</pre><p><strong class="example">Example 3:</strong></p>
15+
<pre><strong>Input:</strong> nums = [], target = 0
16+
<strong>Output:</strong> [-1,-1]
17+
</pre>
18+
<p>&nbsp;</p>
19+
<p><strong>Constraints:</strong></p>
20+
21+
<ul>
22+
<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
23+
<li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li>
24+
<li><code>nums</code> is a non-decreasing array.</li>
25+
<li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li>
26+
</ul>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Approach: Binary Search
2+
3+
# Time: O(log n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def searchRange(self, nums: List[int], target: int) -> List[int]:
8+
lower_bound = self.findBound(nums, target, True)
9+
if lower_bound == -1:
10+
return [-1, -1]
11+
12+
upper_bound = self.findBound(nums, target, False)
13+
14+
return [lower_bound, upper_bound]
15+
16+
def findBound(self, nums: List[int], target: int, isFirst: bool) -> int:
17+
n = len(nums)
18+
begin, end = 0, n - 1
19+
20+
while begin <= end:
21+
mid = (begin + end) // 2
22+
23+
if nums[mid] == target:
24+
if isFirst:
25+
# This means we found our lower bound.
26+
if mid == begin or nums[mid - 1] < target:
27+
return mid
28+
29+
# Search on the left side for the bound.
30+
end = mid - 1
31+
32+
else:
33+
# This means we found our upper bound.
34+
if mid == end or nums[mid + 1] > target:
35+
return mid
36+
37+
# Search on the right side for the bound.
38+
begin = mid + 1
39+
40+
elif nums[mid] > target:
41+
end = mid - 1
42+
43+
else:
44+
begin = mid + 1
45+
46+
return -1

0 commit comments

Comments
 (0)