原题网址:
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
本文介绍了一种解决LeetCode上移除排序数组中多余重复项的问题的方法,允许每个元素最多出现两次。通过增加计数变量来跟踪元素出现次数,实现了对数组的有效处理。
251

被折叠的 条评论
为什么被折叠?



