# Search for a Range

Source: Internet
Author: User

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

Ideas

Search by binary, if not found return [ -1,-1] If you find middle, find start and ending.

`1  Public classSolution {2      Public int[] Searchrange (int[] A,inttarget) {3         BooleanFound =false;4         intLow = 0;5         intHigh = A.length-1;6         intMiddle = 0;7         intResult[] =New int[2];8         9          while(Low <=High ) {TenMiddle = (low + high)/2; One             if(Target >A[middle]) { ALow = middle + 1; -             } -             Else if(Target <A[middle]) { theHigh = Middle-1; -             } -             Else -             { +Found =true; -                  Break; +             } A}// while at         if(!found)//did not find the -         {             -Result[0] = 1; -RESULT[1] = 1; -}//if -         Else{ in              while(Middle >= 0 && a[middle] = =target) { -middle--; to             } +             if(Middle < 0) -Result[0] = 0; the             Else *Result[0] = middle + 1; \$Middle = result[0];Panax Notoginseng              while(Middle < a.length && A[middle] = =target) { -middle++; the             } +             if(Middle >=a.length) ARESULT[1] = a.length-1; the             Else +RESULT[1] = middle-1; -}//Else \$         returnresult; \$     } -}`

Search for a Range

Related Keywords:

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.