zoukankan      html  css  js  c++  java
  • Search for a Range 分类: Leetcode(查找) Leetcode(排序) 2015-04-10 15:34 23人阅读 评论(0) 收藏

    Search for a Range


    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].

     
    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) {
            int i = 0, j = n-1;
            vector<int> vec;
            while( A[i] != target && i < n ) {
                i++;
            }
            while( A[j] != target && j > 0 ) {
                j--;
            }
            
            if( i == n  || j== -1) {
                vec.push_back(-1);
                vec.push_back(-1);
            }
            
            else {
                vec.push_back(i);
                vec.push_back(j);
            }
            
            return vec;
        }
    };

    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) {
            int i = 0, j = n-1;
            vector<int> ret(2,-1);
            
            while(i < j) {
                int mid = (i+j) / 2;
                if (A[mid] < target) i = mid + 1;
                else j = mid;
            }
            
            if (A[i] != target) return ret;
            else ret[0] = i;
            
            j = n-1;
            while(i < j) {
                int mid = (i+j+1) /2 ;
                if (A[mid] > target) j = mid-1;
                else i = mid;
            }
            ret[1] = j;
            return ret;
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    C#中 ()=>的含义
    大白话系列之C#委托与事件讲解(三)
    大白话系列之C#委托与事件讲解(二)
    C#委托
    php.ini
    mac 登陆phpmyadmin 提示 mysqli_real_connect(): (HY000/2002): No such file or directory
    mac 安装 mysql 5.7
    Mac下的PHP的配置与运行
    phpstorm 2019.1 mac
    激活 phpstorm2019.1 win10
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656939.html
Copyright © 2011-2022 走看看