s0034
This commit is contained in:
parent
38a20a3c7f
commit
9fc414b433
@ -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
|
@ -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};
|
||||
}
|
@ -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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user