题目描述:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
题目翻译:给定一个数组A和一个值elem,删除所有的elem,并返回新的数组长度。元素的顺序可以改变。
C语言版:
int removeElement(int A[], int n, int elem) { int j = 0; for(int i = 0; i < n; i++){ if (A[i] != elem) A[j++] = A[i]; } return j; }
Python版:
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): j = 0 for i in A : if i != elem : A[j] = i j += 1 return j