leetcode/src/s0035_search_insert_position.cpp

34 lines
678 B
C++
Raw Normal View History

2022-11-21 13:32:04 +00:00
#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;
}
}