移除元素python3(leetcode27)

#移除元素leetcode27

#给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数#组的新长度。

#不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。

#元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        j = 0
        for i in range(0, len(nums)):

            if nums[i] != val:
                nums[j] =nums[i]
                j +=1
        return j

Supongo que te gusta

Origin blog.csdn.net/ziqingnian/article/details/121785534
Recomendado
Clasificación