diff --git a/include/s0034_find_first_and_last_position_of_element_in_sorted_array.hpp b/include/s0034_find_first_and_last_position_of_element_in_sorted_array.hpp new file mode 100644 index 0000000..3e3955b --- /dev/null +++ b/include/s0034_find_first_and_last_position_of_element_in_sorted_array.hpp @@ -0,0 +1,14 @@ +#ifndef S0034_FIND_FIRST_AND_LAST_POSITION_OF_ELEMENT_IN_SORTED_ARRAY +#define S0034_FIND_FIRST_AND_LAST_POSITION_OF_ELEMENT_IN_SORTED_ARRAY + +#include +#include + +using namespace std; + +class Solution { + public: + vector searchRange(vector& nums, int target); +}; + +#endif diff --git a/src/s0034_find_first_and_last_position_of_element_in_sorted_array.cpp b/src/s0034_find_first_and_last_position_of_element_in_sorted_array.cpp new file mode 100644 index 0000000..d6fae5e --- /dev/null +++ b/src/s0034_find_first_and_last_position_of_element_in_sorted_array.cpp @@ -0,0 +1,39 @@ +#include "s0034_find_first_and_last_position_of_element_in_sorted_array.hpp" + +vector Solution::searchRange(vector& nums, int target) { + int size = nums.size(); + if (size <= 0) { + return vector {-1, -1}; + } else if (size == 1) { + if (nums[0] == target) { + return vector {0, 0}; + } else { + return vector {-1, -1}; + } + } + int left{0}; + int right = size - 1; + int mid; + while (left <= right) { + mid = static_cast(floor((left + right) / 2)); + if (nums[mid] == target) { + int resultLeft, resultRight; + for (int i = mid; i < size; ++i) { + if (nums[i] == target) { + resultRight = i; + } + } + for (int i = mid; i >= 0; --i) { + if (nums[i] == target) { + resultLeft = i; + } + } + return vector {resultLeft, resultRight}; + } else if (nums[mid] > target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return vector {-1, -1}; +} diff --git a/tests/s0034_find_first_and_last_position_of_element_in_sorted_array.cpp b/tests/s0034_find_first_and_last_position_of_element_in_sorted_array.cpp new file mode 100644 index 0000000..ff6142f --- /dev/null +++ b/tests/s0034_find_first_and_last_position_of_element_in_sorted_array.cpp @@ -0,0 +1,27 @@ +#include "s0034_find_first_and_last_position_of_element_in_sorted_array.hpp" + +#include + +TEST(Problem34, Case1) { + vector nums{5, 7, 7, 8, 8, 10}; + int target{8}; + vector o{3, 4}; + Solution solution; + EXPECT_EQ(solution.searchRange(nums, target), o); +} + +TEST(Problem34, Case2) { + vector nums{5, 7, 7, 8, 8, 10}; + int target{6}; + vector o{-1, -1}; + Solution solution; + EXPECT_EQ(solution.searchRange(nums, target), o); +} + +TEST(Problem34, Case3) { + vector nums{}; + int target{0}; + vector o{-1, -1}; + Solution solution; + EXPECT_EQ(solution.searchRange(nums, target), o); +}