Python accepted solution with two pointers


  • 0
    T

    Python accepted two pointers

    class Solution(object):
        def summaryRanges(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            summary = []
            # edge case 1
            if len(nums) == 0:
                return summary
            # edge case 2
            if len(nums) == 1:
                summary.append(str(nums[0]))
                return summary
    
            i = 0 # slow pointer
            j = 1 # fast pointer
            interval = str(nums[0])
            while i < len(nums) - 1 and j < len(nums):
                if nums[j - 1] + 1== nums[j]:
                    interval = str(nums[i]) + '->' + str(nums[j])
                    # move fast pointer, keep the slow pointer in the start number
                    j += 1
                else:
                    if nums[j - 1] == nums[j]:
                        # don't append repeat number into the ranges, only keep the last repeat one
                        # move fast pointer, keep the slow pointer in the start number
                        j += 1
                        continue                
                    summary.append(interval)
                    i = j
                    j += 1
                    interval = str(nums[i])
    
            summary.append(interval)
    
            return summary       
    

  • 0
    R

    while i < len(nums) - 1 seems redundant to me. I think, it would suffice to check j<len(nums)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.