2022-11-21 13:32:04 +00:00
|
|
|
#include "s0035_search_insert_position.hpp"
|
|
|
|
|
2022-11-24 08:44:36 +00:00
|
|
|
// 闭区间写法
|
2022-11-30 10:20:36 +00:00
|
|
|
int S0035::searchInsert1(vector<int>& nums, int target) {
|
2022-11-24 08:44:36 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 开区间写法
|
2022-11-30 10:20:36 +00:00
|
|
|
int S0035::searchInsert2(vector<int>& nums, int target) {
|
2022-11-24 08:44:36 +00:00
|
|
|
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
|
|
|
}
|