zoukankan      html  css  js  c++  java
  • 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 :

  • 相关阅读:
    Ubuntu12.04 安装网卡驱动
    C++类内存分布
    C++多态的实现及原理详细解析
    QT4.7.4在ubuntu10.10下的编译(转)
    FFMpeg处理RTMP流有两种方式
    C++中的单例模式
    C++ STL--stack/queue 的使用方法
    qt编译出现 /usr/bin/ld: cannot find -lQtCore的解决方法
    each()
    window.setTimeout() 和 window.setInterval() 使用说明
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11103234.html
Copyright © 2011-2022 走看看