problem:
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]
.
当指针指向的数小于target时,指针后移;
指针等于target的时候,若为第一次,则将当前位置记录在result中,若不为第一次,则计数器加一。
最后若找到了target,则将末尾位置记录result中,若未找到,则result记录-1.
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result;
result.push_back(-1);
int length = nums.size();
int i = 0;
int flag = 0;
int count = 0;
while(i < length)
{
if(nums[i] < target)
i++;
else if(nums[i] == target && flag == 0)
{
flag = 1;
result[0] = i;
i++;
}
else if(nums[i] == target && flag == 1)
{
count++;
i++;
}
else
break;
}
if(flag == 1)
{
result.push_back(result[0]+count);
}
else
result.push_back(-1);
return result;
}
};