Remove Duplicates in sorted array II
题目描述
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
解题方法
用p1,p2两个指针来计算当前元素重复了几次
Solution
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
newIndex = 0
p1 = 0
p2 = 1
length = len(nums)
while p1 < length:
p2 = p1 + 1
while p2 < length and nums[p1] == nums[p2]:
p2 += 1
times = p2 - p1
if times >= 2:
nums[newIndex] = nums[p1]
newIndex += 1
nums[newIndex] = nums[p1]
newIndex += 1
else:
nums[newIndex] = nums[p1]
newIndex += 1
p1 = p2
return newIndex