原 leetcode python 27.移除元素

本文介绍了如何使用Python解决LeetCode中的27题——移除元素。通过遍历数组,遇到目标值时跳过,重新写入数组,实现最快解法。这种方法类似于快排中的partition操作,利用双指针技巧,将不被删除的元素移动到数组前面。

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

https://leetcode-cn.com/problems/remove-element/description/
遍历一遍遇到要删除的值跳过,将数组重写一遍,这样的最快的。

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        if len(nums) == 0:
            return 0;
        j=0
        for i in range(0,len(nums)):
            if nums[i] != val :
                nums[j] = nums[i]
                j = j + 1
        return j

这个是真没想到。。。。

自己写的方法是,有点类似于快排partition操作,用两个指针,前面遇到要删除的元素时,将数组尾部不被删除的移到前面,直到i>j结束循环

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i= 0
        j= len(nums)-1
        count = 0
        s = 0

        while(1):
            if(i>j):
                break
            if nums[i]==val:
                count+=1
                while(nums[j]==val and j>i):
                    count+=1
                    j=j-1
                nums[i]=nums[j]
                j=j-1
                i+=1
            else:
                i+=1
        return len(nums)-count
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值