-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo.34Search for a Range
48 lines (37 loc) · 1.45 KB
/
No.34Search for a Range
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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]
//my solution
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target)
{
vector<int> res;
if (nums.size() == 0) //若为空,返回【-1,-1】
return { -1,-1 };
vector<int>::iterator result = find(nums.begin(), nums.end(), target); //找到第一个target的位置
if(result!=nums.end()) //如果到不在末尾,插入
res.push_back(result - nums.begin());
else if(nums[nums.size() - 1] == target) //若末尾为target,插入
res.push_back(nums.size() - 1);
else //否则,返回【-1,-1】
return {-1,-1};
if (nums[nums.size() - 1] == target) //判断末尾是否为target,是直接插入,返回
{
res.push_back(nums.size() - 1);
return res;
}
while (nums[result-nums.begin()] ==target ) //若不是,往后移动
{
result++;
}
res.push_back(result - nums.begin()-1);
return res;
}
};