LeetCode9——移除元素

本文提供了两种解决LeetCode9移除元素问题的方法。方法一通过遍历列表并移动非目标值来减少列表长度;方法二使用列表的remove方法删除指定值,最终返回处理后的列表长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode9——移除元素

前言:

在这里插入图片描述


题目内容:

在这里插入图片描述
在这里插入图片描述

示例 1:
在这里插入图片描述

示例 2:
在这里插入图片描述
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-element


python实现:

方法一:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        count  = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[count ] = nums[i]
                print(nums)
                count  += 1
        return count
 
if __name__ == '__main__':
    nums = [1, 1, 2,2,2,3,2,2]
    val=2
    a = Solution()
    print(a.removeElement(nums,val))

方法二:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        for i in range(nums.count(val)):
            nums.remove(val)
        return len(nums)

if __name__ == '__main__':
    nums = [1, 1, 2,2,2,3,2,2]
    val=2
    a = Solution()
    print(a.removeElement(nums,val))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值