AC Python: Simple


  • 0

    Simle python:

    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        duplicate = 0
        
        # add all into set to find the dup and later the sum of the actual series
        unique = set()
        
        unqiue_len = 0
        for num in nums:
            unique.add(num)
            unqiue_len += 1
            
            # only set duplicate once ( 0 is an invalid entry )
            # val was NOT added into the unique set, so this is the duplicate
            if duplicate == 0 and len(unique) != unqiue_len:
                duplicate = num
    
        # missing number is sum of series minus sum of actual
        # (without the duplicate counted twice)
        sum_of_actual = 0
        for val in unique:
            sum_of_actual += val
        
        # n(n+1)/2
        sum_of_series = len(nums) * ( len(nums) + 1 ) // 2
        
        missing_number = sum_of_series - sum_of_actual
        
        return [ duplicate, missing_number ]

Log in to reply
 

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