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"].
cpp:
class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> result; if (nums.empty()) return result; int start = nums[0]; int end = nums[0]; int len = nums.size(); for (int i = 1; i < len; i++) { if ( nums[i] == nums[i - 1] || nums[i] == (nums[i-1]+1)) { end = nums[i]; } else { result.push_back(format(start,end)); start = nums[i]; end = start; } } result.push_back(format(start,end)); return result; } // string format(int begin,int end){ // char buffer[32]; // if(begin == end){ // sprintf(buffer,"%d",begin); // }else{ // sprintf(buffer,"%d->%d",begin,end); // } // return string(buffer); // } string format(int begin,int end){ stringstream ss; if(begin == end){ ss << begin; }else{ ss << begin << "->" << end; } return ss.str(); } };
python:
class Solution(object): def summaryRanges(self, nums): x, size = 0, len(nums); result = [] while x < size: c, r = x, str(nums[x]) while x + 1 < size and nums[x + 1] == nums[x] + 1: x += 1 if x > c: r += "->" + str(nums[x]) result.append(r) x += 1 return result;