Remove Element
Question
Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don't matter.
Have you met this question in a real interview? Yes
Example
Given an array [0,4,4,0,0,2,4,4]
, value=4
return 4
and front four elements of the array is [0,0,0,2]
Thoughts
双指针题,相当于quick select,把不等于elem的放在前面,然后得到结果
Solution
class Solution:
"""
@param A: A list of integers
@param elem: An integer
@return: The new length after remove
"""
def removeElement(self, A, elem):
# write your code here
length = len(A)
numNot = 0
for i in range(length):
if A[i] != elem:
A[numNot] = A[i]
numNot += 1
return numNot