[Leetcode] Search for a Range

Source: Internet
Author: User

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

Problem Solving Ideas:

The test instructions of this problem is to find the subscript range of the target values in the sorted array, which may have the same elements.

The topic requires time complexity in O (Logn). 3-time binary search. For the first time, we find a subscript k with a value of target, a second time to find the smallest subscript with a value of target in 0~k, and the third to find the largest subscript in the k~len-1 with a value of target. The time complexity is O (Logn) per time.

Class Solution {public:vector<int> Searchrange (vector<int>& nums, int target) {VECTOR&LT;INT&G T                Result ({-1,-1});        int start=0, End=nums.size ()-1;        int middle;            Find the first while (Start<=end) {middle= (start+end)/2;                if (nums[middle]==target) {result[0]=result[1]=middle;            Break            }else if (nums[middle]>target) {end=middle-1;            }else{start=middle+1;            }} if (Result[0]!=-1) {//Find the smallest subscript start=0;            End=result[0]-1;                while (start<=end) {middle= (start+end)/2;                    if (nums[middle]==target) {end=middle-1;                Result[0]=middle;                }else{start=middle+1;            }}//Find the largest subscript start=result[1]+1;            End=nums.size ()-1;while (start<=end) {middle= (start+end)/2;                    if (nums[middle]==target) {start=middle+1;                Result[1]=middle;                }else{end=middle-1;    }}} return result; }};


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