Remove Duplicates from Sorted Array II

Question

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?

For example, Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

Thoughts

还是two pointer,不过这里加了条件可以最多重复两次,所以要加一个变量来保持重复的次数

注意点

  • 重复次数的计算
  • pointer和重复次数 reset的时机
  • 最后一个重复的计算

Solution

class Solution:
    """
    @param A: a list of integers
    @return an integer
    """
    def removeDuplicates(self, A):
        # write your code here
        if not A:  
            return 0
        size = 0   
        i = 0      
        j = 0      
        while j < len(A):   
            if A[j] == A[i]:
                j += 1      
            else:  
                numRepe = j - i
                if numRepe >= 2:  
                    A[size] = A[i]
                    size += 1
                    A[size] = A[i]
                    size += 1
                else:       
                    A[size] = A[i]
                    size += 1
                i = j
                j = i
        numRepe = j - i
        if numRepe >= 2:  
            A[size] = A[i]
            size += 1
            A[size] = A[i]
            size += 1
        else:       
            A[size] = A[i]
            size += 1
        return size