Remove Duplicates from Sorted Array II
Description:
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].
Code:
class Solution:
"""
@param: nums: An ineger array
@return: An integer
"""
def removeDuplicates(self, nums):
# write your code
if len(nums) == 0:
return 0
i = 1
j = 0
maxLong = 2
cnt = maxLong-1
while i<len(nums):
if nums[i] == nums[j] and cnt<=0:
i+=1
continue
if nums[i] == nums[j] and cnt>0:
nums[j+1] = nums[i]
i+=1
j+=1
cnt-=1
continue
if nums[i] != nums[j]:
cnt = maxLong-1
nums[j+1] = nums[i]
i+=1
j+=1
continue
return j+1