Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return
[-1, -1]
.
For example,
Given
return
Given
[5, 7, 7, 8, 8, 10]
and target value 8,return
[3, 4]
.class Solution {
public:
int leftMost(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left)/2;
if (nums[mid] == target) {
if (mid == left || nums[mid] != nums[mid - 1]) {
return mid;
} else {
right = mid - 1;
}
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int rightMost(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left)/2;
if (nums[mid] == target) {
if (mid == right || nums[mid] != nums[mid + 1]) {
return mid;
} else {
left = mid + 1;
}
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
ans.push_back(leftMost(nums, target));
ans.push_back(rightMost(nums, target));
return ans;
}
};
No comments:
Post a Comment