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[i]==elem时,将该数组最后一个位置的元素进行交换(最后一个位置随着删除元素,不断的变化)。
public class Solution { public int removeElement(int[] A, int elem) { int len = A.length-1; int i = 0; int temp; while(i <= len){ if(A[i] == elem){ temp = A[len]; A[len] = A[i]; A[i] =temp; --len; } else{ i++; } } return len+1; } }