Summary Ranges

Problem: Summary Ranges

The general idea to solve this problem is to hold a head for a string to find a tail for it. If no tail is found, then append the string to the result directly. We can use a trick by adding one more number to the list to output last number properly.

Code in Python:

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        res = []
        if not nums:
            return res
        head = nums[0]
        nums += [nums[-1]+2]
        for i in xrange(1, len(nums)):
            if nums[i] - nums[i-1] > 1:
                if nums[i-1] == head:
                    res.append(str(head))
                else:
                    res.append(str(head) + '->' + str(nums[i-1]))
                head = nums[i]
        return res

results matching ""

    No results matching ""