[LeetCode] 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"].
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Easy的题,要非常速度地写出bug free的代码!
1 class Solution { 2 public: 3 vector<string> summaryRanges(vector<int>& nums) { 4 vector<string> res; 5 if (nums.empty()) return res; 6 string s; 7 int start = nums[0], end = nums[0]; 8 for (int i = 1; i <= nums.size(); ++i) { 9 if (i < nums.size() && nums[i] == end + 1) { 10 end = nums[i]; 11 } else { 12 if (start == end) s = to_string(start); 13 else s = to_string(start) + "->" + to_string(end); 14 res.push_back(s); 15 if (i < nums.size()) start = end = nums[i]; 16 } 17 } 18 return res; 19 } 20 };