Sharing my 4lines AC python solution using Set


  • 0
    X
    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    
            new = list(set(nums))
            new.sort()
            nums[0:len(new)] = new
            return len(new)
    

    104ms

    comparing with 100ms solution below

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    
            if len(nums) == 0: return 0
                i = 0
                for x in nums:
                    if (nums[i] != x):
                        i += 1
                        nums[i] = x
                return i + 1

  • 0
    S

    In the first solution, whats the purpose of this line,

        nums[0:len(new)] = new
    

    ?


  • 0
    S

    Never mind, it's because the initial question asks you to change the input list in place...


Log in to reply
 

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