一、 问题描述
Leecode第三十四题,题目为:
Given an array of integers nums sorted in ascending order, 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
问题理解为:
说明:
二、算法思路
1、
2、
三、实现代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//vector<int> res;
int a=0;
int b=0;
int i=0;
if (nums.empty())
a=-1;
b=-1;
for(i=0;i<nums.size();i++)
if (nums[i]==target){
a=i;
for(i=a+1;i<nums.size();i++)
if (nums[i]==target){
b=i;
}
}
else
a=-1;
b=-1;
for(i=a+1;i<nums.size();i++)
if (nums[i]==target){
b=i;
}
else b=a;
if (a == nums.size() - 1)
b=a;
return {a,b};
}
};