# [LeetCode] 228. Summary Ranges 总结区间

2021年09月15日 阅读数：1

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

Example 1:java

```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:python

```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.```

Java:app

```class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> list=new ArrayList();
if(nums.length==1){
return list;
}
for(int i=0;i<nums.length;i++){
int a=nums[i];
while(i+1<nums.length&&(nums[i+1]-nums[i])==1){
i++;
}
if(a!=nums[i]){
}else{
}
}
return list;
}
}　　```

Python:post

```class Solution:
# @param {integer[]} nums
# @return {string[]}
def summaryRanges(self, nums):
ranges = []
if not nums:
return ranges

start, end = nums[0], nums[0]
for i in xrange(1, len(nums) + 1):
if i < len(nums) and nums[i] == end + 1:
end = nums[i]
else:
interval = str(start)
if start != end:
interval += "->" + str(end)
ranges.append(interval)
if i < len(nums):
start = end = nums[i]

return ranges　　```

Python:url

```class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""

ranges = []
for n in nums:
if not ranges or n > ranges[-1][-1] + 1:
ranges += [],
ranges[-1][1:] = n,

return ['->'.join(map(str, r)) for r in ranges]　　```

Python:orm

```class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
ranges, r = [], []
for n in nums:
if n-1 not in r:
r = []
ranges += r,
r[1:] = n,
print r, ranges
return ['->'.join(map(str, r)) for r in ranges]
```

C++:htm

```class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
int i = 0, n = nums.size();
while (i < n) {
int j = 1;
while (i + j < n && nums[i + j] - nums[i] == j) ++j;
res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
i += j;
}
return res;
}
};
```

C++:blog

```class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
const int size_n = nums.size();
vector<string> res;
if ( 0 == size_n) return res;
for (int i = 0; i < size_n;) {
int start = i, end = i;
while (end + 1 < size_n && nums[end+1] == nums[end] + 1) end++;
if (end > start) res.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
else res.push_back(to_string(nums[start]));
i = end+1;
}
return res;
}
};
```

[LeetCode] 163. Missing Ranges 缺失区间