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.
翻译:从列表中删除给定的值,不得额外申请内存,返回前N个正确的值即可
思路:在原列表中进行操作,把要删除的元素和后面非目标元素进行互换即可
class Solution(object):
def removeElement(self, nums, val):
if not nums:
return 0
cnt = len(nums)
flag_j = -1
match = 0
for i in range(cnt):
if nums[i] == val:
if i > flag_j:
j = i+1
else:
j = flag_j+1
while(j<cnt):
if nums[j]!=nums[i]:
nums[i] = nums[j]
nums[j] = val
flag_j = j
break
j+=1
for i in range(cnt):
if nums[i] != val:
match+=1
else:
break
return match