题目描述:
34. 在排序数组中查找元素的第一个和最后一个位置
给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
题解
解法一
8ms,13.4MB
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int first = -1;
int last = -1;
for(int i = 0;i<nums.size();i++){
if(nums[i]==target){
first = i;
break;
}
}
reverse(nums.begin(),nums.end());
for(int i = 0;i<nums.size();i++){
if(nums[i]==target){
last = nums.size()-i-1;
break;
}
}
vector<int> v;
v.push_back(first);
v.push_back(last);
return v;
}
};
解法二
12ms,13.4Mb
相比不再reverse,而是直接逆向遍历,用时反而增加
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int first = -1;
int last = -1;
for(int i = 0;i<nums.size();i++){
if(nums[i]==target){
first = i;
break;
}
}
for(int i = nums.size()-1;i>=0;i--){
if(nums[i]==target){
last = i;
break;
}
}
vector<int> v;
v.push_back(first);
v.push_back(last);
return v;
}
};
解法三
4ms,13.3MB
相比解法二,把size单独计算后,用时意外的减少了,
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int first = -1;
int last = -1;
int size= nums.size();
for(int i = 0;i<size;i++){
if(nums[i]==target){
first = i;
break;
}
}
for(int i = size-1;i>=0;i--){
if(nums[i]==target){
last = i;
break;
}
}
vector<int> v;
v.push_back(first);
v.push_back(last);
return v;
}
};
方法四:二分法
8ms,13.3
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int leftborder = getleftborder(nums, target);
int rightborder = getrightborder(nums, target);
// 情况一
if (leftborder == -2 || rightborder == -2)
return {-1, -1};
// 情况三
if (rightborder - leftborder > 1)
return {leftborder + 1, rightborder - 1};
// 情况二
return {-1, -1};
}
int getrightborder(vector<int>& nums,int target){
int left = 0;
int size= nums.size();
int right = size-1;
int rightborder =-2;
while(left<=right){
int mid = left+(right-left)/2;
if(nums[mid]>target){
right = mid-1;
}
else{
left = mid+1;
rightborder = left;
}
}
return rightborder;
}
int getleftborder(vector<int>& nums,int target){
int left = 0;
int size= nums.size();
int right = size-1;
int leftborder =-2;
while(left<=right){
int mid = left+(right-left)/2;
if(nums[mid]>=target){
right = mid-1;
leftborder = right;
}
else{
left = mid+1;
}
}
return leftborder;
}
};