Leetcode 26: Remove Duplicates from Sorted Array

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

Remove Duplicates from Sorted Array

Total Accepted: 87967 Total Submissions: 280545 Difficulty: Easy

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

 

Code

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums)==1:
            return 1
            
        prev = nums[0]
        del_cnt = 0
        for i in xrange(1, len(nums)):
            idx = i- del_cnt
            if nums[idx] == prev:
                nums.pop(idx)
                del_cnt += 1
            else:
                prev = nums[idx]
            
        return len(nums)
        

 

Idea

My code doesn’t only return the length of non-duplicated elements but also pop duplicated elements in the original array.

 

Code that does not need to pop: https://discuss.leetcode.com/topic/3102/my-solution-time-o-n-space-o-1

Leave a comment

Your email address will not be published. Required fields are marked *