Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2842da5

Browse files
committed
Create: 0034-find-first-and-last-position-of-element-in-sorted-array.cpp
1 parent 4fbd191 commit 2842da5

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+
class Solution {
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)