Task3: remove elements

Given an array nums and a value val, you need to place the elements to remove all equal values ​​val, and returns the new length of the array after removal.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Order of the elements may be changed. You do not need to consider beyond the elements of the new array length behind.

Problem solving:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        p = 0  # 定义一个指针标志
        for num in nums:
            if num != val:
                nums[p] = num  # 覆盖数组操作,得到「题目要求的数组」
                p += 1  # 指针后移
        return p   # 返回「题目要求的数组」的长度

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/remove-element
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Released five original articles · won praise 0 · Views 109

Guess you like

Origin blog.csdn.net/weixin_43535441/article/details/104638408