码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode116:search-for-a-range

时间:2020-08-01 12:42:08      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:value   NPU   pre   cli   div   not   param   一维数组   scribe   

题目描述

给出一个有序数组,请在数组中找出目标值的起始位置和结束位置
你的算法的时间复杂度应该在O(log n)之内
如果数组中不存在目标,返回[-1, -1].
例如:
给出的数组是[5, 7, 7, 8, 8, 10],目标值是8,
返回[3, 4].

Given a sorted array of integers, 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].

For example,
Given[5, 7, 7, 8, 8, 10]and target value 8,
return[3, 4].


示例1

输入

复制
[5, 7, 7, 8, 8, 10],8

输出

复制
[3,4]


class Solution {
public:
    /**
     *
     * @param A int整型一维数组
     * @param n int A数组长度
     * @param target int整型
     * @return int整型vector
     */
    vector<int> searchRange(int* A, int n, int target) {
        // write code here
        vector< int> res(2,-1);
        if (A==nullptr || n<=0)
            return res;
        int low=lower_bound(A, A+n, target)-A;
        if (low==n || A[low]!=target)
            return res;
        else res[0]=low;
        int high=upper_bound(A, A+n,target)-A-1;
        res[1]=high;
        return res;
        
    }
};

class Solution {
public:
    /**
     *
     * @param A int整型一维数组
     * @param n int A数组长度
     * @param target int整型
     * @return int整型vector
     */
    vector<int> searchRange(int* A, int n, int target) {
        // write code here
        vector<int> res(2,-1);
        if (A==nullptr || n<=0)
            return res;
        int low=0,high=n-1;
        while (low<=high)
        {
            int middle =(high+low)>>1;
            if (A[middle]<target)
                low=middle+1;
            else
                high=middle-1;
            
        }
        int low2=0,high2=n-1;
        while (low2<=high2)
        {
            int middle2=(high2+low2)>>1;
            if (A[middle2]<=target)
                low2=middle2+1;
            else
                high2=middle2-1;
            
        }
        if (low<=high2){
            res[0]=low;
            res[1]=high2;
            
        }
        return res;
    }
    
};

leetcode116:search-for-a-range

标签:value   NPU   pre   cli   div   not   param   一维数组   scribe   

原文地址:https://www.cnblogs.com/hrnn/p/13413969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!