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/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82144173