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

[LeetCode] Summary Ranges

时间:2015-06-26 14:51:16      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Easy的题,要非常速度地写出bug free的代码!

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

 

[LeetCode] Summary Ranges

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4602111.html

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