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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
# -*- coding:utf-8 -*-
class Solution(object):
def removeElement(self, nums, val):
nums.sort(key=lambda x: 0 if x == val else 1)
flag = 0
for i in range(len(nums)):
if nums[i] != val:
flag = i
break
return len(nums[flag:])
if __name__ == '__main__':
print(Solution().removeElement([3,2,2,3], 3))
'''
def removeElement(self, nums, val):
try:
while True:
nums.remove(val)
except:
return len(nums)
'''
本文介绍了一种在不使用额外空间的情况下从数组中移除指定值的方法,并保持了常数级别的内存消耗。通过排序和遍历的方式实现,示例中展示了如何将数值3从数组中移除并返回新的有效长度。
617

被折叠的 条评论
为什么被折叠?



