[leetcode] 228. Summary Ranges @ python

原题

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.

解法

双指针法

代码

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        ans = []
        if not nums: return ans
        if len(nums) < 2:
            return [str(nums[0])]
        l, r = 0, 1
        while r < len(nums):
            if nums[r] - nums[l] > 1:
                # not continous
                ans.append(str(nums[l]))
                l += 1
                r += 1
            else:
                start = l
                while r+1 < len(nums) and nums[r+1] - nums[r] == 1:
                    r += 1
                ans.append('{}->{}'.format(nums[start], nums[r]))
                l = r+1
                r = r+2
        if l == len(nums)-1:
            ans.append(str(nums[l]))
        return ans

你可能感兴趣的:(Leetcode)