Sunday, August 30, 2015

Leetcode 228. Summary Ranges

https://leetcode.com/problems/summary-ranges/

Solution:
# T:O(n) S:O(n)
class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        if not nums: return []
        i, ret = 0, []
        while i < len(nums):
            start = i
            while i < len(nums) - 1 and nums[i] == nums[i+1] - 1:
                i += 1
            end = i
            if start == end:
                ret.append(str(nums[i]))
            else:
                ret.append(str(nums[start])+"->"+str(nums[end]))
            i += 1
        return ret
Run Time: 56 ms

No comments:

Post a Comment