leetcode[163]Missing Ranges

Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.

For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

需要考虑lower  upper 在数组元素A[i]~A[j]之间的情况,即先用二分查找,找到第一个A[begin]大于等于lower的下标begin,再找到第一个大于等于upper的下标end,若找到,则第一个小于upper的下标为end-1;

string i_tos(int n)

{

    string s="";

    char buf[4];

    s+=itoa(n,buf,10);

    return s;

}

string show(int left, int right)

{

    if(left==right)return i_tos(left);

    else return i_tos(left)+"->"+i_tos(right);

}

//找第一个大于等于value的数组的下标

int iLower(int A[], int left, int right, int value)

{

    while(left<right)

    {

        int mid=(left+right)/2;

        if(value<=A[mid])right=mid;

        else left=mid+1;

    }

    return left;

}

vector<string> findMissingRanges(int A[], int n, int lower, int upper) 

{

    vector<string> res;

    if(n==0||upper<A[0]||lower>A[n-1])

        res.push_back(show(lower,upper));

    else

    {

        int begin=iLower(A, 0, n-1, lower);

        if(lower<A[begin])res.push_back(show(lower,A[begin]-1));

        int end=iLower(A,begin,n-1,upper);

        if(upper<=A[end])end--;

        for (int i=begin;i<end;i++)

        {

            if(A[i+1]-A[i]==1)continue;

            res.push_back(show(A[i]+1,A[i+1]-1));

        }

        res.push_back(show(A[end]+1,upper));

    }

    return res;

}

之前没有考虑lower upper 在数组元素A[i]~A[j]之间,以下为之前的代码:

1). 为空,lower upper 之间关系。

2). lower A[0]  之间关系

3). A[i]~A[i+1]  之间关系

4). A[A.length-1] ~ upper 之间关系

string i_tos(int n)

    {

        string s="";

        char buf[4];

        s+=itoa(n,buf,10);

        return s;

    }

    vector<string> findMissingRanges(int A[], int n, int lower, int upper) 

    {

        vector<string> res;

        string str="";

        if(n==0)

        {

            if(upper-lower>=1) str+=i_tos(lower)+"->"+i_tos(upper);

            else str+=i_tos(lower);

            if(str!="")res.push_back(str);

        }

        else

        {

            if (lower<A[0])

            {

                if(A[0]-lower>1)str+=i_tos(lower)+"->"+i_tos(A[0]-1);

                else    str+=i_tos(lower);

                if(str!="")res.push_back(str);

            }

            for (int i=1;i<n;i++)

            {

                if(A[i]-A[i-1]>2) str+=i_tos(A[i-1]+1)+"->"+i_tos(A[i]-1);

                else if(A[i]-A[i-1]==2) str+=i_tos(A[i-1]+1);

                if(str!="")res.push_back(str);

                str="";

            }

            if(upper>A[n-1])

            { 

                if(upper-A[n-1]>1) str+=i_tos(A[n-1]+1)+"->"+i_tos(upper);

                else str+=i_tos(upper); 

                if(str!="")res.push_back(str);

            }

        }

        return res;

    }

 

你可能感兴趣的:(LeetCode)