Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
1.定义一个count指针,index 指针
2.当重复的时候index 增加
3.当不重复的时候A[]count= A[index]
1. need two pointers one count another index
2. when duplicated index+=1
when no duplicated A[count]=A[index]
code is as follow
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
count=0
if len(A)<=1:
return len(A)
index=1
count=0
while index<len(A):
if A[count]==A[index]:
index+=1
else:
count+=1
A[count]=A[index]
index+=1
return count+1
本文介绍了一种在不使用额外空间的情况下从已排序数组中去除重复元素的方法。通过两个指针count和index,当遇到不同元素时进行替换并更新计数。最终返回不含重复项的新数组长度。
476

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



