34. Find First and Last Position of Element in Sorted Array/在排序数组中查找元素的第一个和最后一个位置

Share
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]

AC代码

class Solution {
public:
    vector searchRange(vector& nums, int target) {
        vector res;
        auto it1 = lower_bound(nums.begin(), nums.end(), target);
        auto it2 = upper_bound(nums.begin(), nums.end(), target);
        if (it1 == it2) {
            res.push_back(-1);
            res.push_back(-1);
        }
        else {
            res.push_back(it1 - nums.begin());
            res.push_back(it2 - nums.begin() - 1);
        }
        return res;
    }
};

总结

学习了lower_bound和upper_bound两个STL函数

你可能感兴趣的:(34. Find First and Last Position of Element in Sorted Array/在排序数组中查找元素的第一个和最后一个位置)