Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cf0e236

Browse files
#34. Find First and Last Position of Element in Sorted Array
1 parent cb32eb7 commit cf0e236

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Given an array of integers nums sorted in non-decreasing order, find the
2+
# starting and ending position of a given target value.
3+
4+
# If target is not found in the array, return [-1, -1].
5+
6+
# You must write an algorithm with O(log n) runtime complexity.
7+
8+
9+
10+
# Example 1:
11+
12+
# Input: nums = [5,7,7,8,8,10], target = 8
13+
# Output: [3,4]
14+
# Example 2:
15+
16+
# Input: nums = [5,7,7,8,8,10], target = 6
17+
# Output: [-1,-1]
18+
# Example 3:
19+
20+
# Input: nums = [], target = 0
21+
# Output: [-1,-1]
22+
23+
24+
# Constraints:
25+
26+
# 0 <= nums.length <= 105
27+
# -109 <= nums[i] <= 109
28+
# nums is a non-decreasing array.
29+
# -109 <= target <= 109
30+
31+
32+
from typing import List
33+
from bisect import bisect_left
34+
class Solution:
35+
def searchRange(self, nums: List[int], target: int) -> List[int]:
36+
l = bisect_left(nums, target)
37+
r = bisect_left(nums, target + 1)
38+
39+
if l == r:
40+
return -1, -1
41+
else:
42+
return l, r-1

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /