难度: Easy
原题连接
内容描述
Given an array nums and a value val, 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 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.
思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(1)******
极其暴力。。。
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
while val in nums:
nums.remove(val)
return len(nums)
思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******
如果当前数字等于val,就把当前数字换成数组的最后一个数字,然后删除掉数组最后一个数字,这样可以实现时间O(N)了
beats 100%
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
idx = 0
while idx < len(nums):
if nums[idx] == val:
nums[idx] = nums[-1]
del nums[-1]
else:
idx += 1
return len(nums)
补充一下,开始我还用nums = nums[:-1]
来代替del nums[-1]
,但是这道题的nums是pass by reference,所以我们切片的时候nums地址变化了,这样是不对的