27. Remove Element@python

Given an array nums and a value val, remove all instances of that value in-place and return the new length.this

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.spa

The order of elements can be changed. It doesn't matter what you leave beyond the new length.指針

題目地址: Remove Elementcode

難度: Easyblog

題意: 刪除指定值,並將其餘元素移動前面ip

思路:element

遍歷,雙指針leetcode

代碼:rem

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

時間複雜度: O(n)get

空間複雜度: O(1)

相關文章
相關標籤/搜索