返回信息流https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
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],
Your function should return length = 2, and A is now [1,2].
于是我就直接写了个这个~~
但是提示错误了,
Input: [1,1,2]
Output: [1,1]
Expected: [1,2]
求大神指点下~~
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
return len(set(A))
这是一条镜像帖。来源:北邮人论坛 / python / #4838同步于 2015/1/13
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
leetcode一道想用python做,不过wrong answer
buptmuye
2015/1/13镜像同步19 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
def removeDuplicates(self, A):
A = list(set(A))
return len(A)
可是这样也是提示同样的错误呀,好奇怪 A = list(set(A))应该就变成[1,2]了吧
Input: [1,1,2]
Output: [1,1]
Expected: [1,2]
【 在 Chon 的大作中提到: 】
: 需要将A的值修改为[1, 2]
建议先去了解一下Python中关于按引用传递的相关知识,本版之前有过相关讨论。
在这个问题中,对A的「赋值操作」实质上是将另一个对象,即list(set(A)),的引用赋予了A,并不会改变A所引用的原来的对象的内容。
【 在 buptmuye 的大作中提到: 】
: def removeDuplicates(self, A):
: A = list(set(A))
: return len(A)
: ...................
来自「北邮人论坛手机版」
谢谢你
【 在 Chon 的大作中提到: 】
: 建议先去了解一下Python中关于按引用传递的相关知识,本版之前有过相关讨论。
: 在这个问题中,对A的「赋值操作」实质上是将另一个对象,即list(set(A)),的引用赋予了A,并不会改变A所引用的原来的对象的内容。
: 来自「北邮人论坛手机版」
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if len(A) == 0:
return 0
p1 = 1
p2 = 1
while p2 < len(A):
if A[p2] == A[p2 - 1]:
p2 += 1
else:
A[p1] = A[p2]
p2 += 1
p1 += 1
return p1
感觉确实只能用修改元素的方式来处理,但你的解法要求重复出现的数必须是连续的
【 在 Aut 的大作中提到: 】
: class Solution:
: # @param a list of integers
: # @return an integer
: ...................