题目链接
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
题目原文
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.
题目大意
给定一个排好序的数组。修改这个数组使得每个数最多可以出现两次。返回去掉多余重复数组后的长度,当然将多余重复数放到数组后面并不影响。
解题思路
(借鉴)使用两个指针prev和curr,判断A[curr]是否和A[prev]、A[prev-1]相等,如果相等curr指针继续向后遍历,直到不相等时,将curr指针指向的值赋值给A[prev+1],这样多余的数就都被交换到后面去了。最后prev+1值就是数组的长度
代码
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 2:
return len(nums)
prev = 1
curr = 2
while curr < len(nums):
if nums[curr] == nums[prev] and nums[curr] == nums[prev - 1]:
curr += 1
else:
prev += 1
nums[prev] = nums[curr]
curr += 1
return prev + 1