zoukankan      html  css  js  c++  java
  • 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 left=searchleft(A,0,n-1,target);
            int right=searchright(A,0,n-1,target);
            vector<int> v;
            v.push_back(left);
            v.push_back(right);
            return v;
        }
        int searchleft(int A[],int l,int r,int target)
        {
            if(l>r) return -1;
            int m=(l+r)/2;
            if(A[m]==target)
            {
                int index=searchleft(A,l,m-1,target);
                if(index==-1)   return m;
                else return index;
            }
            else if(A[m]>target) return searchleft(A,l,m-1,target);
            else return searchleft(A,m+1,r,target);
        }
        int searchright(int A[],int l,int r,int target)
        {
            if(l>r) return -1;
            int m=(l+r)/2;
            if(A[m]==target)
            {
                int index=searchright(A,m+1,r,target);
                if(index==-1)   return m;
                else return index;
            }
            else if(A[m]>target) return searchright(A,l,m-1,target);
            else return searchright(A,m+1,r,target);
        }
    }; 
  • 相关阅读:
    POJ 1475 推箱
    POJ 2253 Frogger
    POJ 1970 The Game
    POJ 1979 Red and Black
    HDU 1546 Idiomatic Phrases Game 求助!help!!!
    Fibonacci 1
    BZOJ 1041
    椭圆曲线质因数分解
    奇怪的高精度
    数论v2
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759326.html
Copyright © 2011-2022 走看看