"Leetcode" Search for a Range

Source: Internet
Author: User

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 is in the order of O(log n).

If the target is not a found in the array, return [-1, -1] .

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

Due to O (logn) time requirements, it is obvious to find with two points.

The idea is to use a binary search to find one of the target, not found then return [-1,-1]

After finding it, the two-point search is extended from this position to both sides recursively.

Part of the reference to the idea of xiao.he.587.

classSolution { Public: Vector<int> Searchrange (intA[],intNinttarget) {Vector<int> Ret (2, -1); intIND = Helper (A,0, N-1, Target); if(Ind! =-1)        {//Find one target            intleft =IND; intright =IND; ret[0] =Left ; ret[1] =Right ; //recursively extend left towards 0             while(left = Helper (A,0, left-1, target))! =-1) ret[0] =Left ; //recursively extend right towards n-1             while(right = Helper (A, right+1, N-1, target))! =-1) ret[1] =Right ; }        returnret; }    intHelper (intA[],intLowintHighinttarget) {//binary Search         while(Low <=High ) {            intMID = low + (high-low)/2; if(A[mid] = =target)returnmid; Else if(A[mid] >target) high= mid-1; Else Low= mid+1; }        return-1; }};

"Leetcode" Search for a Range

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.