Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
分析
这一题的难点在于考虑边界条件,在检验的case中会有INT_MAX这样的可能会导致int over-flow的数。由于数组时递增的,所以在判断是不是相等的时候使用nums[i] - 1 == nums[i-1]。
在nums的尾部增加一个数字方便处理。
Code
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
int length = nums.size();
if (length == 0)
return res;
int start = nums[0];
int len = 1;
nums.push_back(0);
for (int i = 1; i <= length; i ++)
{
if (i < length && nums[i] -1 == nums[i-1])
{
len ++;
continue;
}
string tmp;
if (len > 1)
{
tmp.append(to_string(start));
tmp.append("->");
tmp.append(to_string(nums[i-1]));
}
else
{
tmp.append(to_string(start));
}
res.push_back(tmp);
start = nums[i];
len = 1;
}
return res;
}
};
运行效率
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Summary Ranges.
Memory Usage: 8.5 MB, less than 85.32% of C++ online submissions for Summary Ranges.