LeetCode 228. Summary Ranges【未加入列表】

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

 

思路不难,从头到尾,从头到尾数数字,然后看是否连续就行, 这个答案是我在高票回答的评论中找到的,感觉写的通俗易懂,非常棒!

https://leetcode.com/problems/summary-ranges/discuss/63284/10-line-c%2B%2B-easy-understand

 1   vector<string> summaryRanges(vector<int>& nums) {
 2         vector<string> res;
 3         
 4         for (int i = 0, n = nums.size(); i < n; i++) {    
 5             int begin = nums[i];
 6             while (i != (n - 1) && nums[i] == nums[i + 1] - 1)
 7                 i++;
 8             int end = nums[i];
 9             if (begin == end) 
10                 res.push_back(to_string(begin));
11             else 
12                 res.push_back(to_string(begin)  + "->" + to_string(nums[i])); 
13         }
14         
15         return res;
16     }

 

posted @ 2019-02-25 22:04  皇家大鹏鹏  阅读(117)  评论(0编辑  收藏  举报