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

This paper uses the idea of binary algorithm to find the start and end position of target. Time: 17ms. The code is as follows:

`classSolution { Public:    intSearchfrange (vector<int>& Nums,intFintLinttarget) {        if(F > L | | nums[l]! =target)returnL +1; if(Nums[f] = =target)returnF; intMID = f + (L-F)/2; if(Nums[mid] = =target)returnSearchfrange (Nums, F, mid-1, Target); Else            returnSearchfrange (Nums, Mid +1, L, Target); }    intSearchlrange (vector<int>& Nums,intFintLinttarget) {        if(F > L | | nums[f]! =target)returnF-1; if(Nums[l] = =target)returnl; intMID = f + (L-F)/2; if(Nums[mid] = =target)returnSearchlrange (Nums, Mid +1, L, Target); Else            returnSearchlrange (Nums, F, mid-1, Target); } Vector<int> Searchrange (vector<int>& Nums,intFintLinttarget) {        if(F > L | | target < NUMS[F] | | target >Nums[l])returnvector<int> (2, -1); Vector<int> Range (2,-1); intMID = f + (L-F)/2; if(Nums[f] = =target) {range[0] =F; range[1] = Searchlrange (Nums, f+1, L, Target); returnrange; }        if(Nums[l] = =target) {range[0] = Searchfrange (Nums, F, L-1, Target); range[1] =l; returnrange; }        if(Nums[mid] = =target) {range[0] = Searchfrange (Nums, F, mid-1, Target); range[1] = Searchlrange (nums, Mid +1, L, Target); returnrange; }        Else if(Nums[mid] <target)returnSearchrange (Nums, Mid +1, L, Target); Else            returnSearchrange (Nums, F, mid-1, Target); } Vector<int> Searchrange (vector<int>& Nums,inttarget) {        if(Target<nums.front () | | target>nums.back ())returnvector<int> (2, -1); returnSearchrange (Nums,0, Nums.size ()-1, Target); }};`

[Leetcode] #34 Search for a Range

Related Keywords:

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.