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.
思路:
(1)遍历数组,若数组元素A[i]与elem相等,则将数组最后一个元素替换A[i],数组长度减一(相当于取代A[i]位置)
(2)由于最后一个数组元素也可能等于elem,因此需要再次判断当前位置(替换后的A[i]),执行i--操作,使循环回到当前遍历位置
//遍历数组,若数组元素A[i]与elem相等,则将数组最后一个元素替换A[i],数组长度减一(相当于取代A[i]位置)
//由于最后一个数组元素也可能等于elem,因此需要再次判断当前位置(替换后的A[i]),执行i--操作,使循环回到当前遍历位置
public class Solution {
public int removeElement(int[] A, int elem) {
if(A == null || A.length == 0)
return 0;
int len = A.length;
for(int i = 0; i < len; i++){
if(A[i] == elem){
A[i] = A[len-1];
len--;
i--;
}
}
return len;
}
}