This commit is contained in:
Sainnhe Park 2022-11-21 21:10:37 +08:00
parent 38a20a3c7f
commit 9fc414b433
3 changed files with 80 additions and 0 deletions

View File

@ -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 <vector>
#include <cmath>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target);
};
#endif

View File

@ -0,0 +1,39 @@
#include "s0034_find_first_and_last_position_of_element_in_sorted_array.hpp"
vector<int> Solution::searchRange(vector<int>& nums, int target) {
int size = nums.size();
if (size <= 0) {
return vector<int> {-1, -1};
} else if (size == 1) {
if (nums[0] == target) {
return vector<int> {0, 0};
} else {
return vector<int> {-1, -1};
}
}
int left{0};
int right = size - 1;
int mid;
while (left <= right) {
mid = static_cast<int>(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<int> {resultLeft, resultRight};
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return vector<int> {-1, -1};
}

View File

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