首页 > 代码库 > LeetCode--Remove Element

LeetCode--Remove Element

这个题目没有动手实践,仅仅是想了个思路。结果一看讨论区的代码瞬间感觉,我想的太复杂了。ps:有点想不明确,既然是要移除元素。为何不留下一个不含删除元素的纯净数组。

题目:

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. 


讨论区解决的方法:

public class Solution {
    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];
                startPosition++;
            }
        }
        return startPosition;
    }
}


LeetCode--Remove Element