50. leetCode27:Remove Element

【题目】:

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 by modifying the input array in-place with O(1) extra memory.

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

Example:

Given nums = [3,2,2,3], val = 3,

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

【参考】:参考资料

【思路】:需要限制在O(1)的额外空间

1.使用两个指针i和j,i是慢指针,j是快指针。当nums[j]等于val时,j继续往下走,直到走到nums[j]不等于val,此时将nums[j]的值赋给nums[i],并将i和j同时+1。总得来说,就是通过j指针来遍历nums列表,找到的不等于val的值从头开始放置在列表中。i的值就是删除val后所有的剩余元素长度

2.考虑像[1,2,3,4,5],val=5这样的情况,1-4不需要移动。所以第一种思路的做法会引起额外的移动开销。由于数组中的元素顺序是可以被改变的,因此如果当前元素的值与val相同,就与nums中的最后一个元素进行交换,再从当前位置进行比较;若当前元素的值与val不相同,则直接往下走即可。

【Python代码1】:

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i, j = 0, 0
        length = len(nums)
        while j < length:
            if val == nums[j]:
                j += 1
            else:
                nums[i] = nums[j]
                i += 1
                j += 1
        return i
        

【Python代码2】:

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        length = len(nums)
        while i < length:
            if nums[i] == val:
                nums[i] = nums[length-1]
                length -= 1
            else:
                i += 1
        return length
       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值