zoukankan      html  css  js  c++  java
  • leetcode34. Search for a Range

    问题描述:

    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]

    问题思路:

    这道题要求我们找到target在数组中的下标范围,若不存在则返回[-1, -1], 给出的数组为递增数组

    考察我们如何判定该坐标为范围开始坐标以及范围结束坐标

    注意边界:当target出现在最后一个位置的时候

    代码:

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            vector<int> ret(2,-1);
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] == target){
                    if(ret[0] == -1){
                        ret[0] = i;
                    }
                    continue;
                }
                if(nums[i] != target && ret[0] != -1 && ret[1] == -1)
                    ret[1] = i-1;
            }
            if(ret[0] != -1 && ret[1] == -1){
                ret[1] = nums.size() - 1;
            }
            return ret;
        }
    };
  • 相关阅读:
    vmareworkstation 15 安装密钥
    Linux进入ftp界面退出方法
    linux安装mysql(5.1.73)
    安装http服务,用http搭建web网
    telnet远程连接
    yum出现问题解决方法
    samba
    nfs搭建
    解决VMwareworkstation无法在windows上运行
    2 shell编程
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9109891.html
Copyright © 2011-2022 走看看