zoukankan      html  css  js  c++  java
  • leetcode[34]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:
    int find(int A[],int n, int target, int Left, int Right, int flag)
    {
        if (A==NULL||n==0||Left>Right)return -1;
        int mid=(Left+Right)/2;
        if (A[mid]==target)
        {    
            int pos=flag?find(A,n,target,Left,mid-1,flag):find(A,n,target,mid+1,Right,flag);
            if(pos==-1)
                return mid;
            else 
                return pos;
        }
        else if (A[mid]>target)
        {
            find(A,n,target,Left,mid-1,flag);
        }
        else
        {
            find(A,n,target,mid+1,Right,flag);
        }
    }
    vector<int> searchRange(int A[], int n, int target) 
    {
        vector<int> res;
        int lef=find(A,n,target,0,n-1,1);
        int rig=find(A,n,target,0,n-1,0);
        res.push_back(lef);
        res.push_back(rig);
        return res;
    }
    };
  • 相关阅读:
    ios资源
    学习swift开源项目
    学习di'z地址
    IOS基础库
    IT自学论坛
    HVTableView 分享组
    IOS中的动画菜单
    iOS 通讯录操作
    ios中autolayout
    ios 程序学习
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283605.html
Copyright © 2011-2022 走看看