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

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

Example 1:code

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:orm

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.

 

思路不難,從頭至尾,從頭至尾數數字,而後看是否連續就行, 這個答案是我在高票回答的評論中找到的,感受寫的通俗易懂,很是棒!blog

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

 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     }
相關文章
相關標籤/搜索