简繁EN

LeetCodeNo. 114

【LeetCode with Python】 80. Remove Duplicates from Sorted Array II

目录

题目

原题页面:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
题目类型:Array, Two Pointers
难度评价:Medium

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类似,只是一个元素可以重复出现最多两次,因此可以模仿Remove Duplicates from Sorted List II的解法。


代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if None == A:
return 0
len_A = len(A)
if len_A <= 1:
return len_A

m = 0
n = 1
count = 1
while n < len_A:
if A[m] != A[n]:
count = 1
m += 1
if m != n:
A[m] = A[n]
elif count >= 2:
count += 1
else:
m += 1
count += 1
if m != n:
A[m] = A[n]
n += 1
return m + 1

本文地址:https://xnerv.wang/leetcode-remove-duplicates-from-sorted-array-ii/