leetcode/src/s0035_search_insert_position.cpp
2022-11-30 18:20:36 +08:00

38 lines
697 B
C++

#include "s0035_search_insert_position.hpp"
// 闭区间写法
int S0035::searchInsert1(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;
} else {
return m;
}
}
return r + 1;
}
// 开区间写法
int S0035::searchInsert2(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;
}
}
return r;
}