## 题目描述：

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

## Python代码：

class Solution:
# @param {integer[]} nums
# @return {string[]}
def summaryRanges(self, nums):
x, size = 0, len(nums)
ans = []
while x < size:
c, r = x, str(nums[x])
while x + 1 < size and nums[x + 1] - nums[x] == 1:
x += 1
if x > c:
r += "->" + str(nums[x])
ans.append(r)
x += 1
return ans

Solution 1

Just collect the ranges, then format and return them.

def summaryRanges(self, nums):
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]

Solution 2

A variation of solution 1, holding the current range in an extra variable r to make things easier.

def summaryRanges(self, nums):
ranges, r = [], []
for n in nums:
if n-1 not in r:
r = []
ranges += r,
r[1:] = n,
return ['->'.join(map(str, r)) for r in ranges]

Solution 3

A tricky short version.

def summaryRanges(self, nums):
ranges = r = []
for n in nums:
if `n-1` not in r:
r = []
ranges += r,
r[1:] = `n`,
return map('->'.join, ranges)

Pingbacks已关闭。

1. coder 发布于 2015年11月26日 18:08 #

Solution 1

Just collect the ranges, then format and return them.

def summaryRanges(self, nums):
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]

为什么会有逗号？没逗号就报错？！ｗｈｙ? thx!

2. 在线疯狂 发布于 2015年11月26日 22:11 #

ranges += [], 等价于ranges.append([])
ranges += [] 等价于ranges.extend([])