美文网首页
27. Remove Element

27. Remove Element

作者: FlyCharles | 来源:发表于2019-03-03 23:24 被阅读0次

Array, In-palce, Two pointer

1. 我的AC

方法一:remove 函数

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

方法二

  • in-palce 算法:输出结果覆盖输入,比如,数组 nums 的不断被覆盖
  • 遇到一个目标数,放到 end 指针之后

要注意的是LeetCode中这一类的题目虽然让你return的是一个int长度值,但它会检查nums的内容,其实要求的不仅仅是return的结果,还有对数组的修改

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        start, end = 0, len(nums) - 1
        while start <= end:
            if nums[start] == val:
                nums[start], nums[end] = nums[end], nums[start]
                end = end - 1
            else:
                start +=1
        return start

2. 小结

  1. 删除数组某个元素
nums.remove(val)

相关文章

网友评论

      本文标题:27. Remove Element

      本文链接:https://www.haomeiwen.com/subject/nqgmuqtx.html