s0035
This commit is contained in:
parent
d7a0d6cfe3
commit
68ca2ebbc9
14
include/s0035_search_insert_position.hpp
Normal file
14
include/s0035_search_insert_position.hpp
Normal 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
|
33
src/s0035_search_insert_position.cpp
Normal file
33
src/s0035_search_insert_position.cpp
Normal 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;
|
||||
}
|
||||
}
|
27
tests/s0035_search_insert_position.cpp
Normal file
27
tests/s0035_search_insert_position.cpp
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user