Remove Element

这道题的思路和remove duplicate基本一样,一个指针维护不需要删除的区域,一个指针遍历,背下来比较好

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if not nums:
            return 0

        index = 0
        for i in xrange(len(nums)):
            if nums[i] != val:
                nums[index] = nums[i]
                index += 1

        return index

上面这种方法对数组的修改很多,几乎是每次都修改了,下面有一种修改次数更少的O(n)算法,这种算法只针对指定位置改变数组而不会对数组进行滚动式的修改

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        index = 0
        n = len(nums)

        while index < n:
            if nums[index] == val:
                nums[index] = nums[n - 1]
                n -= 1
            else:
                index += 1

        return index

results matching ""

    No results matching ""