题目简介
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 nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question.
python代码
def if_dp():
#判断是否有重复的
last = yield
#在主函数中next过去了
cur = yield False
#调用的时候返回false表示第一个值的传入而last = none
#所以不等 返回空 实现l[0] = l[0]
while True:
next = yield (last == cur)
last,cur = cur,next
def delete_dup(l,p):
i = 0
for j in range(0,len(l)):
if p(l[j]):
continue
l[i] = l[j]
i += 1
return i
def remove_dp(A):
p = if_dp()
next(p)
return delete_dup(A,p.send)
#p.send生成一个object 每一次调用该对象时候
#将会yield 并且yield的返回值返回给变量
python代码.思路
1.第一次的时候并没有在while循环中
两个值 last = none cur = 第一次传入的值 l[0]
返回值为False;l[i] = l[j]
2.第二次的时候,在while循环中,由于cur 和 last的值不同所以返回false
移动 i 并赋值,(i的位置的值不重要重要的是是否移动,next的值为判断的根据)
每一次都是i先移动 ,然后判断是否继续移动,如果继续移动则代表与前面的值不同