[Locked] Missing Ranges

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Locked] Missing Ranges相关的知识,希望对你有一定的参考价值。

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

分析:

  直接遍历即可,特别要注意的是,边界情况需要想清楚

代码:

vector<string> missingRanges(vector<int> &num, int lower, int upper) {
    vector<string> mr;
    //1、为空时直接返回范围
    if(num.empty()) {
        mr.push_back(lower == upper ? to_string(lower) : to_string(lower) + "->" + to_string(upper));
        return mr;
    }
    //2、前面留有空隙
    if(num.front() > lower)
        mr.push_back(num.front() - 1 == lower ? to_string(lower) : to_string(lower) + "->" + to_string(num.front() - 1));
    //3、中间留有空隙
    for(int i = 1; i < num.size(); i++) {
        if(num[i] == num[i - 1] + 1)
            continue;
        int first = num[i - 1] + 1, last = num[i] - 1;
        mr.push_back(first == last ? to_string(first) : to_string(first) + "->" + to_string(last));
    }
    //4、最后留有空隙
    if(num.back() < upper)
        mr.push_back(num.back() + 1 == upper ? to_string(upper) : to_string(num.back() + 1) + "->" + to_string(upper));
    return mr;
}

 

以上是关于[Locked] Missing Ranges的主要内容,如果未能解决你的问题,请参考以下文章

User status is locked 请翻译一下 准确点,分多

the account is locked怎么解决

the account is locked怎么解决

the account is locked怎么解决

[Locked] Paint Fence

[Locked] Alien Dictionary