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"].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) { | |
vector<string> res; | |
if(nums.size()==0||nums[0]!=lower) | |
nums.insert(nums.begin(), lower-1); | |
if(nums[nums.size()-1]!=upper) | |
nums.insert(nums.end(), upper+1); | |
for(int p=0;p<nums.size()-1; p++){ | |
if(nums[p+1]-nums[p]>2){ | |
string s(to_string(nums[p]+1)+string("->")+to_string(nums[p+1]-1)); | |
res.push_back(s); | |
} | |
if(nums[p+1]-nums[p]==2){ | |
string s(to_string(nums[p]+1)); | |
res.push_back(s); | |
} | |
} | |
return res; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) { | |
vector<string> res; | |
if(nums.size()==0||nums[0]!=lower) | |
nums.insert(nums.begin(), lower-1); | |
if(nums[nums.size()-1]!=upper) | |
nums.insert(nums.end(), upper+1); | |
for(int i=1; i<nums.size(); i++){ | |
int lb = nums[i-1]+1; | |
int rb = nums[i]-1; | |
if(lb==rb) | |
res.push_back(to_string(lb)); | |
if(lb<rb) | |
res.push_back(to_string(lb)+string("->")+to_string(rb)); | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment