[算法题] Remove Element

本文介绍了一道LeetCode上的经典题目——移除数组中特定值的所有实例,并保持原地修改,返回新长度。通过快慢指针技巧实现,避免使用额外空间,符合常数级内存要求。

题目内容

本题来源:LeetCode

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

Do not allocate extra space for another array, you must do this in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

题目思路

题目难度:easy

此题虽然不难,但是蕴含的思想非常重要。这个题目就是数组快慢指针的思想来源。设定两个指针,i和ii,其中i是慢指针,ii是快指针。初始化的时候,ii和i均等于0。快指针遍历所有的数组,当nums[ii]!=val,则将nums[ii]赋值给nums[i],然后i+=1。此时i就是删除了指定元素后的数组长度。

Python代码

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

 

转载于:https://www.cnblogs.com/chengyuanqi/p/7131308.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值