# 34. Find First and Last Position of Element in Sorted Array

## 刷题内容

• https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

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 **- ʱ�临�Ӷ�: O(lgn)*- �ռ临�Ӷ�: O(1)***

���͵Ķ内容描述��Ȳ���Ŀ内容描述�Ƿ���target���ڷֱ�����ҵ�һ�����ֵ�target�����һ��target��

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0,r = nums.size();
vector<int> ans = {-1,-1};
int mid = -1;
while(l < r)
{
mid = (r + l) / 2;
if(nums[mid] < target)
l = mid + 1;
else if(nums[mid] > target)
r = mid;
else
break;
}
if(mid == -1 || nums[mid] != target)
return ans;
int mid1 = l = mid;
r = nums.size();
while(l < r)
{
mid = (r + l) / 2;
if(mid == nums.size())
break;
if(nums[mid] > target)
r = mid;
else
l = mid + 1;
}
if(nums[mid] > target)
mid--;
ans[1] = mid;
l = 0;
r = mid1 + 1;
while(l < r)
{
mid = (r + l) / 2;
if(nums[mid] < target)
l = mid + 1;
else
r = mid;
}
if(nums[mid] < target)
mid++;
ans[0] = mid;
return ans;
}
};


˼·2 **- ʱ�临�Ӷ�: O(lgn)*- �ռ临�Ӷ�: O(1)***

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto pos1 = lower_bound(nums.begin(),nums.end(),target);
vector<int> ans = {-1,-1};
if(pos1 == nums.end() || (*pos1) != target)
return ans;
ans[0] = pos1 - nums.begin();
auto pos2 = upper_bound(nums.begin(),nums.end(),target);
ans[1] = pos2 - nums.begin() - 1;
return ans;
}
};


apachecn/AiLearning