首页 > 其他 > 详细

Summary Ranges

时间:2016-07-31 01:44:46      阅读:236      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!