Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

The full question, and I'm starting to learn python online but having issue with this question marked as 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 by modifying the input array in-place with O(1) extra memory.

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        k=0
        for i in range(i+1,len(nums)-1):
            j=i+1

            for j in range(j+1,len(len(nums))):
                if nums[i] == nums[j]:
                    del nums[j]
        len_list = nums
        return(len_list, nums)
like image 347
tim Avatar asked Dec 03 '22 20:12

tim


2 Answers

First answer from @BoarGules is the best one. But we can do it in forward direction also.

a = [1,1,1,3,4,5,5,5,5,7,7,7,9,9]
i =0
l = len(a)-1
while i < l :
    if a[i] == a[i+1]:
        del a[i+1]
        l -=1
    else :
        i +=1    
print(a)

Result will be :

[1, 3, 4, 5, 7, 9]
like image 23
Hamza Sahib Avatar answered Dec 06 '22 09:12

Hamza Sahib


It is fairly easy, once you realize you have to work from the end of the list, so that your deletions do not change the part of the list you have not yet examined.

a = [1,1,1,3,4,5,5,5,5,7,7,7,9,9]
for i in range(len(a)-1,0,-1):
    if a[i] == a[i-1]:
        del a[i]

Result is

[1, 3, 4, 5, 7, 9]
like image 110
BoarGules Avatar answered Dec 06 '22 09:12

BoarGules