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.
python获取数组长度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对象⾃带的⽅法:unt()、ve()
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
coun = unt(val)
for index in range(coun):
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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论