码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[163]Missing Ranges

时间:2015-02-06 21:46:55      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

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

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);
    }
    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[163]Missing Ranges

标签:

原文地址:http://www.cnblogs.com/Vae1990Silence/p/4278036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!