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

**<font color=red>难度:Medium<font>**

## 刷题内容
> 原题连接

* 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。

```cpp
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)******

由于我们用的是c++，所以这里可以用lower_bound和upper_bound

```cpp
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;
    }
};
```