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 be in the orderO(LogN).

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

 

This article mainly deals with binary search, imitating lower_bound and upper_bound in STL. The general flow of the algorithm is to search for the target in binary search. If the target cannot be found, the system returns [-1,-1], find the first number equal to the target in the left half, and find the first number greater than the target in the right half.

1 class solution {2 public: 3 vector <int> searchrange (int A [], int N, int target) {4 vector <int> ans (2,-1 ); 5 If (! A | n <1) return ans; 6 int left = 0, Right = n-1; 7 while (left <= right) {8 int mid = left + (right-left) /2; 9 If (target = A [Mid]) {10 ans [0] = lower_bound (A, left, mid-1, target ); 11 ans [1] = upper_bound (A, Mid + 1, right, target)-1; 12 Return ans; 13} 14 if (target> A [Mid]) left = Mid + 1; 15 else right = mid-1; 16} 17 return ans; 18} 19 20 int lower_bound (int A [], int left, int right, int target) {// find the first number equal to target 21 While (left <= right) {22 int mid = left + (right-left)/2; 23 if (target> A [Mid]) Left = Mid + 1; 24 else right = mid-1; 25} 26 return right + 1; 27} 28 29 int upper_bound (int A [], int left, int right, int target) {// find the first number greater than target 30 While (left <= right) {31 int mid = left + (right-left)/2; 32 If (target> = A [Mid]) Left = Mid + 1; 33 else right = mid-1; 34} 35 return left; 36} 37 };

 

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.