This commit is contained in:
2022-11-21 21:32:04 +08:00
parent d7a0d6cfe3
commit 68ca2ebbc9
3 changed files with 74 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
#include "s0035_search_insert_position.hpp"
int Solution::searchInsert(vector<int>& nums, int target) {
int size = nums.size();
if (size == 0) {
return 0;
}
int left{0};
int right = size - 1;
int mid;
while (left <= right) {
mid = static_cast<int>(floor((left + right) / 2));
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if (right < 0) {
return 0;
} else if (left > size - 1) {
return size;
}
if (target < nums[right]) {
return right;
} else if (target > nums[left]) {
return left + 1;
} else {
return left;
}
}