题目:
给定一个增序排列数组 nums ,你需要在 原地 删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
思路:每次比较相邻两位,相同时,看last的值是否也与之相同,如果相同则满足条件,删除对应值;若不同则更新last。
本人解法:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
pos = 0
last = -100000 #当出现两次相同时,将last记录为对应值,作为重复次数大于2的判断标准
while pos < len(nums):
if pos > 0:
if nums[pos] == nums[pos-1]:
if nums[pos] == last:
del nums[pos] #删除
pos -= 1
else:
last = nums[pos]
pos += 1
return len(nums)
官方答案:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Initialize the counter and the second pointer.
j, count = 1, 1
# Start from the second element of the array and process
# elements one by one.
for i in range(1, len(nums)):
# If the current element is a duplicate,
# increment the count.
if nums[i] == nums[i - 1]:
count += 1
else:
# Reset the count since we encountered a different element
# than the previous one
count = 1
# For a count <= 2, we copy the element over thus
# overwriting the element at index "j" in the array
if count <= 2:
nums[j] = nums[i]
j += 1
return j