163. Missing Ranges (Medium)
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], 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"]
.
Solution:
要考虑overflow, 这里要用long
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
long l = lower; // first missing integer
vector<string> res;
for (int i = 0; i <= nums.size(); ++i) {
// current occurred integer
long r = (i == nums.size() || nums[i] > upper) ? (long)upper+1:nums[i];
if (l == r) ++l; // not missing
else if (l < r) {
res.push_back((r == l+1) ? to_string(l):to_string(l)+"->"+to_string(r-1));
l = r+1;
}
if (r >= upper) break;
}
return res;
}