From : https://leetcode.com/problems/search-for-a-range/
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].
Hide Similar Problems
Solution :
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start=0, end=nums.size()-1;
vector<int> ans(2);
ans[0]=ans[1]=-1;
while(start <= end) {
int mid = (start+end)>>1;
if(nums[mid] == target) {
for(int i=mid; i>=start; i--) {
if(nums[i] == target) {
ans[0] = i;
}
}
for(int i=mid; i<=end; i++) {
if(nums[i] == target) {
ans[1] = i;
}
}
break;
}
if(nums[mid] > target) {
end = mid-1;
} else {
start = mid+1;
}
}
return ans;
}
};
本文介绍了一个算法问题:在已排序的整数数组中查找给定目标值的起始和结束位置,若未找到则返回[-1,-1]。该算法的时间复杂度为O(log n),并提供了一个具体的C++实现案例。
445

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



