Skip to content

Commit baf989a

Browse files
committed
"Search for a Range"
1 parent 80504cd commit baf989a

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
254254
| 37 | [Sudoku Solver] | |
255255
| 36 | [Valid Sudoku] | [C](src/36.c) |
256256
| 35 | [Search Insert Position] | [C](src/35.c) |
257-
| 34 | [Search for a Range] | |
257+
| 34 | [Search for a Range] | [C++](src/34.cpp) |
258258
| 33 | [Search in Rotated Sorted Array] | [C](src/33.c) |
259259
| 32 | [Longest Valid Parentheses] | |
260260
| 31 | [Next Permutation] | |

src/34.cpp

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
vector<int> searchRange(vector<int>& nums, int target) {
9+
vector<int> ans(2);
10+
int n = nums.size();
11+
int low = 0;
12+
int high = n - 1;
13+
int mid;
14+
bool found = false;
15+
while (low <= high) {
16+
mid = low + (high - low) / 2;
17+
if (nums[mid] == target) {
18+
found = true;
19+
break;
20+
}
21+
else if (nums[mid] < target) {
22+
low = mid + 1;
23+
}
24+
else {
25+
high = mid - 1;
26+
}
27+
}
28+
29+
if (found) {
30+
low = high = mid;
31+
while (low >= 0 && nums[low] == target) low--;
32+
while (high <= n - 1 && nums[high] == target) high++;
33+
34+
ans[0] = low + 1;
35+
ans[1] = high - 1;
36+
}
37+
else {
38+
ans[0] = ans[1] = -1;
39+
}
40+
41+
return ans;
42+
}
43+
};
44+
45+
int main () {
46+
vector<int> nums = {5, 7, 7, 8, 8, 10};
47+
int target = 8;
48+
Solution s;
49+
50+
vector<int> ans = s.searchRange(nums, target);
51+
52+
for (int i = 0; i < ans.size(); i++) {
53+
printf("%d ", ans[i]);
54+
}
55+
printf("\n");
56+
57+
return 0;
58+
}

0 commit comments

Comments
 (0)