leetcode/src/s0035_search_insert_position.cpp

38 lines
703 B
C++
Raw Normal View History

2022-11-21 13:32:04 +00:00
#include "s0035_search_insert_position.hpp"
2022-11-24 08:44:36 +00:00
// 闭区间写法
int Solution1::searchInsert(vector<int>& nums, int target) {
int len = nums.size();
int l{0};
int r = len - 1;
while (l <= r) {
int m = (l + r) >> 1;
if (target < nums[m]) {
r = m - 1;
} else if (nums[m] < target) {
l = m + 1;
2022-11-21 13:32:04 +00:00
} else {
2022-11-24 08:44:36 +00:00
return m;
2022-11-21 13:32:04 +00:00
}
}
2022-11-24 08:44:36 +00:00
return r + 1;
}
// 开区间写法
int Solution2::searchInsert(vector<int>& nums, int target) {
int len = nums.size();
int l{0};
int r = len;
while (l < r) {
int m = (l + r) >> 1;
if (target < nums[m]) {
r = m;
} else if (nums[m] < target) {
l = m + 1;
} else {
return m;
}
2022-11-21 13:32:04 +00:00
}
2022-11-24 08:44:36 +00:00
return r;
2022-11-21 13:32:04 +00:00
}