码迷,mamicode.com
首页 > 其他好文 > 详细

Summary Ranges

时间:2016-07-31 01:44:57      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Summary Ranges

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5722232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!