Problem Definition:
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"].
My Solution:
1 class Solution: 2 # @param {integer[]} nums 3 # @return {string[]} 4 def summaryRanges(self, nums): 5 sr=[] 6 n=len(nums) 7 if n==0: 8 return sr 9 start,end=0,0 10 p=1 11 while p<n: 12 if (nums[p]-nums[p-1])>1: 13 end=p-1 14 if start==end: 15 sr.append(str(nums[start])) 16 else: 17 sr.append(str(nums[start])+"->"+str(nums[end])) 18 start=p 19 p+=1 20 end=p-1 21 if start==end: 22 sr.append(str(nums[start])) 23 else: 24 sr.append(str(nums[start])+"->"+str(nums[end])) 25 return sr
而后在讨论区发现一个短小精悍的写法,显然我对Python太不熟练啦:
1 def summaryRanges(self, nums): 2 ranges, r = [], [] 3 for n in nums: 4 if n-1 not in r: 5 r = [] 6 ranges += r, 7 r[1:] = n, 8 return ['->'.join(map(str, r)) for r in ranges]
crux:
python的赋值和引用