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; }