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"].

 

Analyse: 

Check whether neighbouring numbers are continuous. Push a number into the array first to avoid overflow. 

 1 class Solution {
 2 public:
 3     vector<string> summaryRanges(vector<int>& nums) {
 4         vector<string> result;
 5         if(nums.empty()) return result;
 6         
 7         int n = nums.size();
 8         nums.push_back(nums[n - 1]);
 9         n++;
10         for(int i = 0; i < n - 1; i++) {
11             int start = nums[i];
12             while(i < n - 1 && nums[i] + 1 == nums[i + 1])
13                 i++;
14             int end = nums[i];
15             
16             if(start == end)
17                 result.push_back(to_string(start));
18             else
19                 result.push_back(to_string(start) + "->" + to_string(end));
20         }
21         return result;
22     }
23 };

 

posted @ 2016-07-31 01:01  amazingzoe  阅读(118)  评论(0编辑  收藏  举报