L1-删除排序数组中的重复数字 II

跟进“删除重复数字”:

如果可以允许出现两次重复将如何处理?

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
"""
@param: nums: An ineger array
@return: An integer
"""
#def removeDuplicates(self, nums):
# write your code here
def removeDuplicates(self,A):
i = 1
j = 0
count = 1
while(i <len(A)):
if A[i] == A[j] and count == 2:
A.pop(i)
elif A[i] == A[j]:
count+=1
j+=1
i+=1 //注意i+=1不能放在最外面
else:
count = 1
j+=1
i+=1

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:  
"""
@param A: a list of integers
@return an integer
"""
def removeDuplicates(self, A):
if len(A) <= 1:
return len(A)
temp = A[0]
count, index = 1, 1
while index != len(A):
if A[index] == temp and count == 2:
A.pop(index)
elif A[index] == temp:
count += 1
index += 1
else:
temp = A[index]
count = 1
index += 1
return index + 1
# write your code here

思路

同上题,快慢指针的思想,用i来遍历数组,j来检查重复元素
如果相同且count已经为2,则移出遍历的该元素
如果相同出现一次,count++,快慢指针同时后移
如果不同,则count置1,快慢指针同时后移