原题网址:
https://leetcode.com/problems/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 nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
题解:
和 Remove Duplicates from Sorted Array 的解法一致,只是需要加一个变量记录一下元素出现的次数。
代码:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length==0:
return 0
count = 0
j = 1
for i in range(1,length):
if nums[i]==nums[i-1]:
count += 1
if count==1:
nums[j]=nums[i]
j += 1
if nums[i]!=nums[i-1]:
nums[j]=nums[i]
j +=1
count = 0
return j