27. Remove Element

题目

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.

题意

删除指定的元素,不开辟新的列表,同26题

Python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
k=0
i=0
while i<len(nums):
if nums[i]!=val:
nums[k]=nums[i]
k+=1
i+=1
return k
如果觉得有帮助,给我打赏吧!