美文网首页
每天(?)一道LeetCode(4) Remove Elemen

每天(?)一道LeetCode(4) Remove Elemen

作者: 失业生1981 | 来源:发表于2019-01-18 23:00 被阅读0次

Array

027. Remove Element

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

1.去掉数组中等于val的元素
2.返回新数组的长度
3.不要额外空间

Solutions

valnums中时,去掉它

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """

        while val in nums:
                nums.remove(val)
        return len(nums)

或者和3sum closest一样利用两个指标

    def removeElement1(self, A, elem):
        i, last = 0, len(A) - 1
        while i <= last:
            if A[i] == elem:
                A[i], A[last] = A[last], A[i]
                last -= 1
            else:
                i += 1
        return last + 1

相关文章

网友评论

      本文标题:每天(?)一道LeetCode(4) Remove Elemen

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