Summary Ranges
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"].
1 class Solution { 2 public: 3 vector<string> summaryRanges(vector<int>& nums) { 4 vector<string> res; 5 if (nums.empty()) { 6 return res; 7 } 8 int begin = 0, end = 1; 9 while (begin < nums.size()) { 10 if ((end < nums.size() && nums[end] != nums[end - 1] + 1) || end == nums.size()) { 11 string range; 12 if (end - begin == 1) { 13 range = to_string(nums[begin]); 14 } else { 15 range = to_string(nums[begin]) + "->" + to_string(nums[end - 1]); 16 } 17 res.push_back(range); 18 begin = end; 19 } 20 end++; 21 } 22 23 24 return res; 25 } 26 };