[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

下面的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]

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]

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)

 

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

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

评论
  1. coder coder 发布于 2015年11月26日 18:08 #

    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]

    为什么会有逗号?没逗号就报错?!why? thx!

  2. 在线疯狂 在线疯狂 发布于 2015年11月26日 22:11 #

    ranges += [], 等价于ranges.append([])
    ranges += [] 等价于ranges.extend([])

张贴您的评论