LeetCode34: Search for a Range

Source: Internet
Author: User

LeetCode34: Search for a Range

 

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

 

Subscribe to see which companies asked this question


 

// Question requirement: Give a sorted array, find the first position of the target and the last position of the target, and find the first position of the target, index1, respectively, and the position where the target finally appears, index2 // subtract 1 from the position where (target + 1) appears for the first time to obtain the position class Solution {public: vector
 
  
SearchRange (vector
  
   
& Nums, int target) {int index1 = lower_bound (nums, target); int index2 = lower_bound (nums, target + 1)-1; // use (target + 1) subtract 1 from the first position to obtain the final position of the target if (index1 <nums. size () & nums [index1] = target) return {index1, index2}; else return {-1,-1 };} int lower_bound (vector
   
    
& Nums, int target) {int left = 0, right = nums. size ()-1; while (left <= right) {int mid = (right + left)/2; if (nums [mid] <target) left = mid + 1; else right = mid-1 ;}return left ;}};
   
  
 


 


 

 

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.