228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:
  [0,1,2,4,5,7]

Output:
 ["0->2","4->5","7"]

Explanation: 
0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:
  [0,2,3,4,6,8,9]

Output:
 ["0","2->4","6","8->9"]

Explanation: 
2,3,4 form a continuous range; 8,9 form a continuous range.

Thoughts:

  1. record number a as nums[i], if there is a next number and the next number is continuous; update i.
  2. check the nums[i] with original; if it is not equal (i was updated -> add string "a" + "->" + "nums[i]")

else (i was not updated ->only add string "a").

Code

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        n = len(nums)
        i = 0
        ret = []
        while i < n:
            e = '{}'.format(nums[i])
            a = nums[i]
            while i + 1 < n and nums[i] + 1 == nums[i+1]:
                i = i + 1
            if a != nums[i]:
                ret.append(e + '->' + "{}".format(nums[i]))
            else:
                ret.append(e)
            i = i + 1
        return ret

results matching ""

    No results matching ""