• 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 :

  • 相关阅读:
    Kali Linux软件更新日报20190622
    Maltego更新到4.2.4.12374
    Kali Linux又增加一个顶级域名kali.download
    Nessus提示API Disabled错误
    数据包分析中Drop和iDrop的区别
    快速识别Hash加密方式hashid
    识别哈希算法类型hash-identifier
    vue实现前端导出excel表格
    vue自动化单元测试
    Mock制作假数据
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11103234.html
Copyright © 2020-2023  润新知