AC Python solution. However, its running at 136ms. Any improvement ideas?


  • 0
    F

    Solution works. Code is easy to understand, but it kind of slow. Any ideas for optimization?

    class Solution:
        # @param {integer[]} nums
        # @return {integer}
        def removeDuplicates(self, nums):
            
            if len(nums) <= 1:
                return len(nums)
            
            end = len(nums)-1
            
            while(end > 0):
                
                if(nums[end] == nums[end-1]):
                    nums.pop(end)
                
                end-=1
            
            return len(nums)

  • 5
    L

    Try not to modify list along the way, cause that's costly. Try this:

    class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def removeDuplicates(self, nums):
        if nums == []:
            return 0
        lastitem = nums[0]
        m, n = 1, 1
        for n in range(len(nums)):
            x = nums[n]
            if x != lastitem:
                lastitem = x
                nums[m] = x
                m += 1
        del nums[m:]
        return len(nums)

Log in to reply
 

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