Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given
[0,1,2,4,5,7]
, return["0->2","4->5","7"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> ans; string range; if(nums.size() == 0) return ans; int prev = nums[0]; int start = nums[0]; //nums.push_back(0x80000000);//sentinel BUG HERE, MAY OVERFLOW for(int i = 1; i < nums.size(); i++){ int num = nums[i]; if(num - prev == 1){ //continual prev = num; } else{ //interval if(start == prev){ //single number range.clear(); range.append(to_string(start)); ans.push_back(range); } else{ //range numbers range.clear(); range.append(to_string(start)); range.append("->"); range.append(to_string(prev)); ans.push_back(range); } start = prev = num; } } if(start == prev){ //single number range.clear(); range.append(to_string(start)); ans.push_back(range); } else{ //range numbers range.clear(); range.append(to_string(start)); range.append("->"); range.append(to_string(prev)); ans.push_back(range); } return ans; } };