This commit is contained in:
Sainnhe Park 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,14 @@
#ifndef S0035_SEARCH_INSERT_POSITION_HPP
#define S0035_SEARCH_INSERT_POSITION_HPP
#include <vector>
#include <cmath>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target);
};
#endif

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;
}
}

View File

@ -0,0 +1,27 @@
#include "s0035_search_insert_position.hpp"
#include <gtest/gtest.h>
TEST(Problem35, Case1) {
vector<int> nums{1, 3, 5, 6};
int target{5};
int o{2};
Solution solution;
EXPECT_EQ(solution.searchInsert(nums, target), o);
}
TEST(Problem35, Case2) {
vector<int> nums{1, 3, 5, 6};
int target{2};
int o{1};
Solution solution;
EXPECT_EQ(solution.searchInsert(nums, target), o);
}
TEST(Problem35, Case3) {
vector<int> nums{1, 3, 5, 6};
int target{7};
int o{4};
Solution solution;
EXPECT_EQ(solution.searchInsert(nums, target), o);
}