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

    思路:二分查找法,找到目标值的范围,时间复杂度在O(logn)。先找出左边第一个等于目标值的位置,再找出右边最后一个等于目标值的位置,然后返回这个范围。

    class Solution {
    public:
        int findleft(int A[],int n,int target)
        {
            if(n==0)
                return -1;
            int left=0;
            int right=n-1;
            while(left<right)
            {
                int mid=(left+right)>>1;
                if(A[mid]>=target)
                    right=mid;
                else
                    left=mid+1;
            }
            if(target==A[left])
                return left;
            else
                return -1;
        }
        int findright(int A[],int n,int target)
        {
            if(n==0)
                return -1;
            int left=0;
            int right=n-1;
            while(left<=right)
            {
                int mid=(left+right)>>1;
                if(A[mid]>target)
                    right=mid-1;
                else
                    left=mid+1;
            }
            if(A[right]==target)
                return right;
            else 
                return -1;
        }
        vector<int> searchRange(int A[], int n, int target) {
            vector<int> result(2);
            result.clear();
            for(int i=0;i<2;i++)
                result.push_back(-1);
            int left=findleft(A,n,target);
            int right=findright(A,n,target);
            result[0]=left;
            result[1]=right;
            return result;
        }
    };
  • 相关阅读:
    hdu 2196(树上点分治)
    hdu 4807(网络流 + 贪心)
    hdu4101
    hdu4216
    hdu 4219, 树形概率DP
    hdu 4127 A*搜索
    hdu 4126
    hdu 5296,15年多校1-7
    poj3436 ACM Computer Factory
    Fence
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3674761.html
Copyright © 2011-2022 走看看