Remove Element
Question
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.
Tags
- Array
- Two Pointers
Thought
Reference: https://discuss.leetcode.com/topic/27777/simple-python-o-n-two-pointer-in-place-solution/9
Use the two pointers traversal from the two sides of the array and swap the item if the first item is equal to val.
Code
# use two pointers and swap
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
start, end = 0, len(nums) - 1
while start <= end:
if nums[start] == val:
nums[start], nums[end] = nums[end], nums[start]
end -= 1
else:
start += 1
nums = nums[:start]
return start