1 题目
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.
Array Two Pointers2 思路
好吧,感觉这个题目出的不是很好,按照题目要求,要改变A数组的长度,我一想,数组长度怎么改。。,看了答案,原来只是把和elem相同的元素,取另外一个元素覆盖这个相同的元素即可。也就是结果应该是前面startPosition(最终返回的结果)个元素里面没有elem,且是A[]数组里面排出elem剩下的元素。
3 代码
public int removeElement(int[] A, int elem) { int startPosition = 0; for (int i = 0; i < A.length; i++) { if (A[i] != elem) { A[startPosition++] = A[i]; } } return startPosition; }