Yes, write list to itself (Python)


  • 0
    B
    class Solution:
        # @param A a list of integers
        # @return an integer
        # 
        def removeDuplicates(self, A):
            if len(A)<=1:
                return len(A)
            
            cur=0
            count=0
            old=A[0]
            
            for probe in range(len(A)):
                if A[probe]==old:
                    count+=1
                elif A[probe]!=old:
                    inc=0
                    while inc<min(2,count):
                        A[cur]=old
                        cur+=1
                        inc+=1
                    count=1
                    old=A[probe]
            
            inc=0
            
            while inc<min(2,count):
                A[cur]=old
                cur+=1
                inc+=1
            
            return cur
    

    Writing to itself makes the problem in-place.. As long as the to-write content is shorted than examined-content. By replacing 2 in min(2,count) with any k, this problem is easily extended to at most k times.


Log in to reply
 

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