Blog Archive

Wednesday, December 16, 2015

[LeetCode]Summary Ranges

[LeetCode]Summary Ranges 



题目描述:

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

题目大意:

给定一组排好序且无重复的整数,返回整数范围的汇总。
例如给定数组 [0,1,2,4,5,7], 返回 ["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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
下面的Python代码短小精悍,摘自LeetCode Discuss
链接地址:https://leetcode.com/discuss/42199/6-lines-in-python

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

本文链接:http://bookshadow.com/weblog/2015/06/26/leetcode-summary-ranges/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

No comments:

Post a Comment