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

(leetcode)Summary Ranges

时间:2015-08-04 13:16:30      阅读:175      评论: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"].

思想很简单 逐个比较前后两个数的差值。

技术分享
 1 class Solution {
 2 public:
 3     vector<string> summaryRanges(vector<int>& nums) {
 4         vector<string> res ;
 5         if(nums.size()<1 ) return res;
 6         int i = 0;
 7         int n = nums.size();
 8         while(i<n)
 9         {
10             int j = 1;
11             while(i+j<n && nums[i] == nums[i+j]-j)    ++j;
12             res.push_back(j<=1?to_string(nums[i]):to_string(nums[i])+"->"+to_string(nums[i+j-1])); 
13             i = i + j;
14         }
15         return res;
16     }
17 };
View Code

(leetcode)Summary Ranges

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4701496.html

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