Inplace Remove Duplicate Values in an Array
- Given an array of numbers nums , modify the array in place so that resulting array will have at most two of the same values. This is similar to the earlier problem of removing duplicates , but in this problem we are allowed to repeat an item if the repitition is only once.
- The array should be modified in place, and the function should return the number of eligible items in the new array.
Solution
Here we use a count to keep track of the repitition, and skip placement only if the count value is 2 or more.
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums)<=2: return len(nums) searchIdx = 1 putIdx = 1 count = 0 for searchIdx in range(1,len(nums)): if nums[searchIdx]==nums[searchIdx-1]: count+=1 else: count = 0 if count<2: nums[putIdx] = nums[searchIdx] putIdx += 1 return putIdx