228. Summary Ranges
题目:
https://leetcode.com/problems/summary-ranges/
难度:
Medium
用一个head和headIdx来记录当前consecutive的开始,一旦不再consecutive,push it in
然后应该可以把代码写的更简单
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
if nums == []:
return []
tmp = []
tmpl = []
head = nums[0]
headIdx = 0
tmpl = [head]
for i in range(1,len(nums)):
#not consective anymore
if nums[i] != head + i - headIdx :
tmp.append(tmpl)
head = nums[i]
headIdx = i
tmpl = []
tmpl.append(head)
#consective nums
else:
tmpl.append(nums[i])
#push the last sequence in
tmp.append(tmpl)
res = []
for t in tmp:
if len(t) == 1:
res.append(str(t[0]))
else:
res.append(str(t[0])+"->" +str(t[-1]))
return res