這個題目沒有動手實踐,只是想了個思路,結果一看討論區的代碼瞬間感覺,我想的太復雜了。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; } }