Python实现"移除元素"的三种方法

给定一个数组nums和值val,删除数组nums中和val相等的元素,返回新数组的长度

不能分配额外的数组空间,只能用O(1)的空间完成本题

数组中元素的顺序可以改变

函数中数组长度L可以超过函数返回长度RL,只需要保证数组前RL个元素和val不相等即可

Example 1:

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

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

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

说明:为什么返回数组长度而不是数组本身?因为数组传递方式为引用。

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

1:pyhton中List对象自带的方法:List.count()、List.remove()

def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        coun = nums.count(val)
        for index in range(coun):
            nums.remove(val)
        return len(nums)

2:移动数组元素,数组前n个元素(与val值不相等)即为返回长度n

def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        count = 0
        for index in range(0,len(nums)):
            if nums[index] != val:
                nums[count] = nums[index]
                count += 1
        return count

3:删除数组中与val值相等的元素

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

算法题来自:https://leetcode-cn.com/problems/remove-element/description/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值