From 68ca2ebbc9366fa9a3906b5f3ef1fb7538a3c3d9 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Mon, 21 Nov 2022 21:32:04 +0800 Subject: [PATCH] s0035 --- include/s0035_search_insert_position.hpp | 14 ++++++++++ src/s0035_search_insert_position.cpp | 33 ++++++++++++++++++++++++ tests/s0035_search_insert_position.cpp | 27 +++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 include/s0035_search_insert_position.hpp create mode 100644 src/s0035_search_insert_position.cpp create mode 100644 tests/s0035_search_insert_position.cpp diff --git a/include/s0035_search_insert_position.hpp b/include/s0035_search_insert_position.hpp new file mode 100644 index 0000000..34a443a --- /dev/null +++ b/include/s0035_search_insert_position.hpp @@ -0,0 +1,14 @@ +#ifndef S0035_SEARCH_INSERT_POSITION_HPP +#define S0035_SEARCH_INSERT_POSITION_HPP + +#include +#include + +using namespace std; + +class Solution { + public: + int searchInsert(vector& nums, int target); +}; + +#endif diff --git a/src/s0035_search_insert_position.cpp b/src/s0035_search_insert_position.cpp new file mode 100644 index 0000000..8aa881f --- /dev/null +++ b/src/s0035_search_insert_position.cpp @@ -0,0 +1,33 @@ +#include "s0035_search_insert_position.hpp" + +int Solution::searchInsert(vector& 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(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; + } +} diff --git a/tests/s0035_search_insert_position.cpp b/tests/s0035_search_insert_position.cpp new file mode 100644 index 0000000..537661a --- /dev/null +++ b/tests/s0035_search_insert_position.cpp @@ -0,0 +1,27 @@ +#include "s0035_search_insert_position.hpp" + +#include + +TEST(Problem35, Case1) { + vector nums{1, 3, 5, 6}; + int target{5}; + int o{2}; + Solution solution; + EXPECT_EQ(solution.searchInsert(nums, target), o); +} + +TEST(Problem35, Case2) { + vector nums{1, 3, 5, 6}; + int target{2}; + int o{1}; + Solution solution; + EXPECT_EQ(solution.searchInsert(nums, target), o); +} + +TEST(Problem35, Case3) { + vector nums{1, 3, 5, 6}; + int target{7}; + int o{4}; + Solution solution; + EXPECT_EQ(solution.searchInsert(nums, target), o); +}