返回信息流27. Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
我是这样做的:
def removeElement(nums, val):
num = len(nums)
for a in nums:
if a == val:
num=num-1
nums.pop(nums.index(a))
print num,nums
当执行removeElement([3,3],3)时 结果却是1,[3],是不是因为循环里不应该用nums直接pop,有点理不清了,求解释。。。
这是一条镜像帖。来源:北邮人论坛 / python / #13537同步于 2016/4/20
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
leetcode第27题这样做为什么不对。。。
upupup123
2016/4/20镜像同步13 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
【 在 upupup123 的大作中提到: 】
: 27. Remove Element
: Given an array and a value, remove all instances of that value in place and return the new length.
: Do not allocate extra space for another array, you must do this in place with constant memory.
: ...................
没对数组用过pop()...类似于C++里迭代器失效?
顺便题干都说了不在乎后面放什么,这摆明了让你把一样的都扔到后面233
我试了下也是这样。不太懂为什么这样,感觉楼主这是用python蛮做啊,list是双端链表,你这样做,时间消耗很大。还是补下数据结构和算法吧,底子要打扎实了,不要盲目刷题。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
begin=0
for i in range(len(nums)):
if nums[i]!=val:
nums[begin]=nums[i]
begin+=1
return begin
s=Solution()
print(s.removeElement([1],3))
【 在 UC1451427216 的大作中提到: 】
: 我试了下也是这样。不太懂为什么这样,感觉楼主这是用python蛮做啊,list是双端链表,你这样做,时间消耗很大。还是补下数据结构和算法吧,底子要打扎实了,不要盲目刷题。
如果是链表这么做很快吧……?O(n)的复杂度……直接删不是很好么?
快是快,但是求index操作慢吧。
【 在 whisperzzzz 的大作中提到: 】
:
: 如果是链表这么做很快吧……?O(n)的复杂度……直接删不是很好么?
【 在 UC1451427216 的大作中提到: 】
: 快是快,但是求index操作慢吧。
查了下……list的实现不是和C++的vector差不多的么……
访问也是O(1)的啊……
【 在 UC1451427216 的大作中提到: 】
: 快是快,但是求index操作慢吧。
啊我知道你说什么了……
他那个直接用enumerate遍历就好了……不用特意求一遍index……
【 在 caicai617 的大作中提到: 】
: 你的序列是[3,3],index是0,把nums[0]pop掉之后,index变成1,这时候超出索引范围,然后就结束了?瞎说的。。。
应该是你说的这样的,不应该将nums在for循环里pop,如果想这样做,也应该是拷贝一个nums来pop,多谢多谢~
【 在 UC1451427216 的大作中提到: 】
: 我试了下也是这样。不太懂为什么这样,感觉楼主这是用python蛮做啊,list是双端链表,你这样做,时间消耗很大。还是补下数据结构和算法吧,底子要打扎实了,不要盲目刷题。
:
: class Solution(object):
: ...................
多谢大神指教,感觉你这种解法好棒,大神算法是看的什么书,有推荐的书或者博客之类的么?