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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
Method
Put two node, when node 1 meet value, remove node 2 to finid the first one which is not the value. Change the position of them.
Pay attention we need the length of the output.
Solution
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
p1 = p2 = 0
flag = 0
while p1 < len(nums):
if nums[p1] == val:
p2 = p1 + 1
while True:
if p2 == len(nums):
return p1
elif nums[p2] == val:
p2 += 1
else:
nums[p1] = nums[p2]
nums[p2] = val
p1 += 1
else:
p1 += 1
近期评论