Leetcode 34. Search for a Range

Source: Internet
Author: User

Search for a Range
    • Total accepted:91570
    • Total submissions:308037
    • Difficulty:medium

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

Idea: two points find the leftmost position of the number that matches the condition, and then traverse backwards to find the interval that satisfies the requirement. Code:
1 classSolution {2  Public:3vector<int> Searchrange (vector<int>& Nums,inttarget) {4         intN=nums.size (), low=0, high=n-1, mid;5vector<int>Res;6          while(low<=High ) {7mid=low+ (high-low)/2;8             if(nums[mid]<target) {9Low=mid+1;Ten             } One             Else{ Ahigh=mid-1; -             } -         } the         if(nums[low]==target) { - res.push_back (low); -              while(Low<n&&nums[low]==target) low++; -Res.push_back (low-1); +         }  -         Else{ +Res.push_back (-1); ARes.push_back (-1); at         } -         returnRes; -     } -};

Leetcode 34. 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.