Movatterモバイル変換


[0]ホーム

URL:


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

Commit2842da5

Browse files
committed
Create: 0034-find-first-and-last-position-of-element-in-sorted-array.cpp
1 parent4fbd191 commit2842da5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
3+
Ex. nums = [5,7,7,8,8,10], target = 8 -> [3, 4] (start position is 3, end position is 4)
4+
5+
Use binary search, firstly binary search left endpoint, then binary search right endpoint.
6+
7+
Time: O(log n)
8+
Space: O(1)
9+
*/
10+
11+
classSolution {
12+
public:
13+
vector<int>searchRange(vector<int>& nums,int target) {
14+
if (nums.empty())return {-1, -1};
15+
int l =0, r = nums.size() -1;
16+
while (l < r) {
17+
int mid = l + r >>1;
18+
if (nums[mid] >= target) r = mid;
19+
else l = mid +1;
20+
}
21+
if (nums[l] != target)return {-1, -1};
22+
int left = l;
23+
24+
l =0, r = nums.size() -1;
25+
while (l < r) {
26+
int mid = l + r +1ll >>1;
27+
if (nums[mid] <= target) l = mid;
28+
else r = mid -1;
29+
}
30+
return {left, r};
31+
}
32+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp