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

description:

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:

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]

answer:

https://blog.csdn.net/MC_007/article/details/80998686

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if (nums.empty()) return {-1, -1};
        if (target < nums[0] || target > nums[nums.size() - 1]) return {-1, -1};
        const int l = distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target));
        const int u = distance(nums.begin(), prev(upper_bound(nums.begin(), nums.end(), target)));
        // 讲真我觉得下面两句不应该这么写,因为如果list中所有值都小于target的话,那就会返回last,再用nums[last]就是不合法的,因为last是超出范围的
        if (nums[l] != target) return {-1, -1}; //如果list中所有值都小于target,就返回last
        else return {l, u};
    }
};

my answer:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if (nums.empty()) return {-1, -1};
        if (target < nums[0] || target > nums[nums.size() - 1]) return {-1, -1};
        const int l = distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target));
        const int u = distance(nums.begin(), prev(upper_bound(nums.begin(), nums.end(), target)));
        if (l == nums.size()) return {-1, -1}; // target bigger than all value in list
        else{
            if (nums[l] != target) return {-1, -1}; // target lower than all value in list
            else return {l, u};
        }
        
    }
};

relative point get√:

hint :

原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11103234.html