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(Log n ).

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

Idea: use binary search. Call the function of the standard library function pai_range:

 1 class Solution { 2 public: 3     vector<int> searchRange( int A[], int n, int target ) { 4         vector<int> ret( 2, -1 ); 5         pair<int*,int*> range = equal_range( A, A+n, target ); 6         if( range.first != range.second ) { 7             ret[0] = range.first-A; 8             ret[1] = range.second-A-1; 9         }10         return ret;11     }12 };


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