题目及要求:
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
示例 1:
给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。
思路:
看到题目的时候,瞬间想到的是跟二十六题的解法思路一样,用赋值替代原有的值。
实际操作:
第一版
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
s = 0
n=len(nums)-nums.count(val)
for i in range(len(nums)):
if nums[i] != val:
nums[s]=nums[i]
s+=1
if nums[-1]==val:
nums[-1]=nums[-2]
return len(nums[:n])
结果出现错误,因为未考虑当nums=[]的情况,所以报错了。
第二版
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
s = 0
n=len(nums)-nums.count(val)
if len(nums)==0:
return 0
for i in range(len(nums)):
if nums[i] != val:
nums[s]=nums[i]
s+=1
if nums[-1]==val:
nums[-1]=nums[-2]
return len(nums[:n])
# return nums
第二版也出现错误了,因为未考虑到当数组里面的元素都相同时的情况,所以die了。
第三版(终极通过版)
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
s = 0
n=len(nums)-nums.count(val)
if len(nums)==0:
return 0
if nums.count(val)==len(nums):
nums=[]
else:
for i in range(len(nums)):
if nums[i] != val:
nums[s]=nums[i]
s+=1
if nums[-1]==val:
nums[-1]=nums[-2]
return len(nums[:n])
最后按惯例发个图,嘿嘿