【问题标题】:One program about Remove Element is accepted but the other is not一个关于删除元素的程序被接受,但另一个不被接受
【发布时间】:2020-01-13 18:05:13
【问题描述】:

leetcode 27. Remove Element的以下两个答案有什么区别? 他们两个都返回相同的输出,但只接受了 no.1。我不知道为什么 no.2 是不可接受的。

输出

#Output
[2,2]

程序

1号

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        for x in nums[:]:
            if x == val:
                nums.remove(x)

        return nums

2号

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        result = [s for s in nums if s != val]
        result = str(result).replace(' ', '')
        return result

【问题讨论】:

  • 他们不返回相同的东西,第二个返回一个字符串并且它不会改变列表
  • 我修好了,但在 leetcode 平台上还是不行。
  • 再说一遍,它不会改变列表
  • 我已经摆脱了len()
  • 你明白我在说什么吗?这不是唯一的问题。同样,您的第二个版本永远不会按照问题指定的方式改变原始列表

标签: python arrays python-3.x list


【解决方案1】:

因为您的第二个函数返回的是字符串的长度,而不是实际列表的长度。

您可以打印出您的结果变量,您会看到它包含诸如左括号和右括号以及逗号之类的字符,所有这些都添加到最终长度中。

【讨论】:

    猜你喜欢
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多