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].
Subscribe to see which companies asked this question
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0, r = nums.size(), pos=-1, left=-1, right=-1;
vector<int> vec;
while(l <= r) {
int mid = (l+r)/2;
if(nums[mid] == target) {
pos = mid;
break;
}
else if(nums[mid] > target) r = mid-1;
else l = mid+1;
}
if(l > r) {
vec.push_back(left);
vec.push_back(right);
return vec;
}
l = 0;
r = pos-1;
while(l <= r && nums[r] >= target) {
int mid = (l+r)/2;
if(nums[mid] < target) l = mid+1;
else if(nums[mid] == target) r = mid-1;
}
left = r+1, right=-1;
l = pos+1;
r = nums.size()-1;
while(l <= r && nums[l] <= target) {
int mid = (l+r)/2;
if(nums[mid] == target) l=mid+1;
else if(nums[mid] > target) r=mid-1;
}
right = l-1;
vec.push_back(left);
vec.push_back(right);
return vec;
}
}
本文介绍了一个算法,该算法能在已排序的整数数组中找到指定目标值的起始和结束位置,采用二分查找实现O(log n)的时间复杂度。
241

被折叠的 条评论
为什么被折叠?



