Skip to content

Commit 7f194d4

Browse files
author
kwu130
committed
feat(src): add 34-searchRange, 35-searchInsert
1 parent 255894b commit 7f194d4

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

‎src/34-searchRange.cpp‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//
2+
// Created by 1412 on 2025/10/21.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
vector<int> searchRange(vector<int>& nums, int target) {
12+
const int l = static_cast<int>(ranges::lower_bound(nums, target) - nums.begin()); // find first >= target
13+
if (l == nums.size() || nums[l] != target) return {-1, -1};
14+
const int r = static_cast<int>(ranges::upper_bound(nums, target) - nums.begin() - 1); // find first > target
15+
return {l, r};
16+
}
17+
};
18+
19+
void test() {
20+
Solution s;
21+
vector<int> nums = {5, 7, 7, 8, 8, 10};
22+
vector<int> expected = {3, 4};
23+
assert(s.searchRange(nums, 8) == expected);
24+
25+
expected = {-1, -1};
26+
assert(s.searchRange(nums, 6) == expected);
27+
28+
nums = {};
29+
expected = {-1, -1};
30+
assert(s.searchRange(nums, 0) == expected);
31+
}
32+
33+
int main() {
34+
test();
35+
return 0;
36+
}

‎src/35-searchInsert.cpp‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//
2+
// Created by 1412 on 2025/10/21.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
int searchInsert(vector<int>& nums, int target) {
12+
const int l = static_cast<int>(ranges::lower_bound(nums, target) - nums.begin());
13+
return l;
14+
}
15+
};
16+
17+
void test() {
18+
Solution s;
19+
vector<int> nums = {1, 3, 5, 6};
20+
assert(s.searchInsert(nums, 5) == 2);
21+
assert(s.searchInsert(nums, 2) == 1);
22+
assert(s.searchInsert(nums, 7) == 4);
23+
}
24+
25+
int main() {
26+
test();
27+
return 0;
28+
}

0 commit comments

Comments
 (0)