题目:Given a sorted array of integers, 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 [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
分析:本身看起来很简单的题目,我到底是怎么写的这么复杂又冗余的。。。
代码:
class Solution {
public:
int searchFirst(vector<int>& nums,int target,int low,int high){
if(nums[high]<target) return -1;
while(low<=high){
if(nums[low]==target) return low;
int mid=low+(high-low)/2;
if(mid==low) {
if(nums[low]==target){
return low;
}
else{
if(nums[high]==target){
return high;
}
else{
return -1;
}
}
}
if(nums[mid]>=target){
high=mid;
}
else{
low=mid;
}
}
return -1;
}
int searchLast(vector<int>& nums,int target,int low,int high){
if(nums[low]>target) return -1;
while(low<=high){
if(nums[high]==target) return high;
int mid=low+(high-low)/2;
if(mid==low){
if(nums[high]==target){
return high;
}
else{
if(nums[low]==target){
return low;
}
else{
return -1;
}
}
}
if(nums[mid]<=target){
low=mid;
}
else{
high=mid;
}
}
return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
int n=nums.size();
vector<int> ret(2,-1);
if(n==0) return ret;
ret[0]=(searchFirst(nums,target,0,n-1));
ret[1]=(searchLast(nums,target,0,n-1));
return ret;
}
};
附上第一次刷题时的代码,然而这个运行时间好像更慢一些:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int m=nums.size();
vector<int> result(2,-1);
int left=0;
int right=m-1;
while(left<right-1){
int mid=left+(right-left)/2;
if(nums[mid]==target){
right=mid;
}
else if(nums[mid]>target){
right=mid;
}
else{
left=mid;
}
}
if(nums[left]==target){
result[0]=left;
}
else if(nums[right]==target){
result[0]=right;
}
else{
return result;
}
left=0;
right=m-1;
while(left<right-1){
int mid=left+(right-left)/2;
if(nums[mid]==target){
left=mid;
}
else if(nums[mid]>target){
right=mid;
}
else{
left=mid;
}
}
if(nums[right]==target){
result[1]=right;
}
else if(nums[left]==target){
result[1]=left;
}
else{
return result;
}
return result;
}
};