标签:
题目:
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"].
答案:
class Solution: # @param {integer[]} nums # @return {string[]} def summaryRanges(self, nums): return_list = [] self.left = 0 self.right = 0 self.length = len(nums) if self.length == 0: return return_list for i in range(1, self.length): if (nums [i] - nums[i-1] != 1): return_list.append(self._get_range(self.left, self.right, nums)), self.left = i self.right = i else: self.right += 1 return_list.append(self._get_range(self.left, self.right, nums)) return return_list def _get_range(self, left, right, nums): if (left == right): return "{}".format(nums[left]) else: return "{}->{}".format(nums[left], nums[right])
心得:
这题并不难,但是我想了比较久,没有考虑到的是这一句。“
if (nums [i] - nums[i-1] != 1):
”
我一直在想怎么样用一个自然数序列和输入序列,进行怎么循环比较,然后,把left和right弄出输出了。但是用两个序列是不必要的,纵向看不行,用横向看,就可以想通了。
标签:
原文地址:http://www.cnblogs.com/ender-cd/p/4611085.html