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.
思路:这题不仅要返回长度,还要把多余数字去掉,不过难度不大,直接上代码
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
length = 1
dup = 1
for i in range(1,len(nums)):
if nums[i] == nums[i-1]:
dup += 1
if dup <= 2:
nums[length] = nums[i]
length += 1
else:
dup = 1
nums[length] = nums[i]
length += 1
return length