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 6f6f61f

Browse files
commit
1 parent 14b157f commit 6f6f61f

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
vector<int> searchRange(vector<int>& nums, int target) {
4+
vector<int> ans(2, -1);
5+
if (nums.empty()) return ans;
6+
7+
// First occurrence
8+
int low = 0, high = nums.size() - 1;
9+
while (low <= high) {
10+
int mid = low + (high - low) / 2;
11+
if (nums[mid] >= target) high = mid - 1;
12+
else low = mid + 1;
13+
if (nums[mid] == target) ans[0] = mid;
14+
}
15+
16+
// Last occurrence
17+
low = 0, high = nums.size() - 1;
18+
while (low <= high) {
19+
int mid = low + (high - low) / 2;
20+
if (nums[mid] <= target) low = mid + 1;
21+
else high = mid - 1;
22+
if (nums[mid] == target) ans[1] = mid;
23+
}
24+
25+
return ans;
26+
}
27+
};

0 commit comments

Comments
(0)

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