码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode#228 Summary Ranges

时间:2015-07-16 13:40:23      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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的赋值和引用

 

LeetCode#228 Summary Ranges

标签:

原文地址:http://www.cnblogs.com/acetseng/p/4650793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!