Leetcode34--->search for a range (to find out what the given value appears in the sorted array)

Source: Internet
Author: User

title: Given a sorted array, find out the scope of the given target value, the complexity of the algorithm is required in O (Logn), and if not found, returns [-1,-1];

Example:

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

Problem Solving Ideas:

When we see the time complexity O (logn), we naturally want to use the two-point method, this problem, we naturally also use a two-point method;

Mid = (start + end)/2; There are three relationships between Target and Nums[mid]:

1) Target <nums[mid], then the latter part is discarded, end = mid-1;

2) Target > Nums[mid], the first half is discarded, start = mid + 1;

3) target = Nums[mid], this situation can not simply discard which half, but to go from the middle to the ends of the traversal, until the boundary is found;

The code is as follows:

1  Public classSolution {2      Public int[] Searchrange (int[] Nums,inttarget) {3         if(Nums = =NULL|| Nums.length < 1)4             return New int[]{-1,-1};5         int[] res =New int[2];6Res[0] = 1;7RES[1] = 1;8         intStart = 0;9         intEnd = Nums.length-1;Ten         intMID = 0; One          while(Start <=end) A         { -Mid = (start + end)/2; -             if(Nums[mid] <target) theStart = mid + 1; -             Else if(Nums[mid] >target) -End = Mid-1; -             Else +             { -Start =mid; +End =mid; A                  while(Start >= 0 && Nums[start] = =target) atstart--; -                  while(End < Nums.length && Nums[end] = =target) -end++; -                 return New int[]{start + 1, end-1}; -             } -         } in         returnRes; -     } to}

Leetcode34--->search for a range (to find out what the given value appears in the sorted array)

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.