[Leetcode#34] Search for a Range

Source: Internet
Author: User

The problem:

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

My Analysis:

The idea behind this question is very elegant and tricky.
Key:when the target value is found, we were not return it (very important). We keep going to reach the the boundry.
It's very skllful to write the right checking condition, and read the "right" value from the proper pointer.
1. When we reach the "the left" most target, we stop the "low pointer" (left pointer).
if (A[mid] < target)//we move the low pointer only then A[mid] is strictly smaller than target.
Low = mid + 1;
else//a[mid] <= target, we keep move high Pinter, even when a[mid] = = target.
High = Mid-1

2. The same idea could is used to find the right most target, we stop the high pointer (right pointer).
if (A[mid] <= target)
Low = mid + 1;
else//a[mid] > target, we move high pointer only if A[MID] is strictly larger than target.
High = mid-1;

My Solution:

 Public classSolution { Public int[] Searchrange (int[] A,inttarget) {                int[] ret =New int[2]; ret[0] = 1; ret[1] = 1; if(A.length = = 0)            returnret; intLlow = 0; intLhigh = a.length-1; intRlow = 0; intRhigh = a.length-1; intMID =-1;  while(Llow <=Lhigh) {Mid= (llow + lhigh)/2; if(A[mid] < target)//The idea behind this approaching is very tricky and elegant!Llow = mid + 1; ElseLhigh= Mid-1; }                 while(Rlow <=Rhigh) {Mid= (Rlow + rhigh)/2; if(A[mid] <=target) Rlow= Mid + 1; ElseRhigh= Mid-1; }                if(Llow <=Rhigh) {ret[0] =llow; ret[1] =Rhigh; }                returnret; }}

[Leetcode#34] 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.