Leetcode--Search for a Range

Source: Internet
Author: User

Q: 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 and [5, 7, 7, 8, 8, 10] target value 8, return [3, 4] .

Analysis: because there are sequential sequences, it should be possible to find by means of dichotomy. Two recursive exits: (1) n=1 and no targets found; (2) The target has been found.
Note the case of TARGET>A[N/2], when the [A+N/2, N-N/2] sub-sequence is re-recursive lookup, the return value of the target position to add the previous N/2.

Class Solution {public:    vector<int> searchrange (int a[], int n, int target) {        vector<int> ret;        if (n = = 1 && target!=a[0])   //Recursive exit 1, the target value            ret.assign (2,-1) is not found;        else if (target = = A[n/2]) {      //Recursive exit 2, locate the target value            int Tbeg = N/2, tend = N/2;            while ((--tbeg) >= 0 && target = = A[tbeg]);            while ((++tend) < n && target = = A[tend]);            Ret.push_back (Tbeg + 1);            Ret.push_back (tend-1);        }        else if (target < A[N/2])            ret = Searchrange (A, N/2, target);        else{    ret = searchrange (A + N/2, N-N/2, target);    if (ret[0] = =-1 && ret[1] = = 1)  return ret;    Ret[0] + = N/2; RET[1] + = N/2;       attention***        }        return ret;}    ;


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.