给定一个数组和一个值,使用就地算法将数组中所有等于这个值的元素删除,并返回新数组的长度。
元素的顺序可以更改。你不用去关心大于当前数组长度的空间里面存储的值
//这里按照调试的评判标准,输出的不为升序数组
int nail = A.length; //注意考虑length-1情况,所以nail不为length-1
if (A.length == 0) {
return 0;
}
for (int index = 0; index < A.length; index++) {
if (A[index] == elem) {
while ((nail > index) && (A[--nail] == elem)) {
//找到index位置后,nail前面的elem
}
A[index]=A[nail];
}
}
return nail; //nail是旧数组后面第一次被换成elem的位置,所以等于新数组的长度
public class Solution {
public int removeElement(int[] A, int elem) {
int i = 0;
int j = A.length-1;
while(i<=j){
if(A[i]==elem){
A[i]=A[j];
j--;
}
else{
i++;
}
}
return j+1;
}
} //遍历数组,若数组元素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;
}
}
public class Solution {
public int removeElement(int[] A, int elem) {
int left = 0;
int right = A.length-1;
while(left<=right) {
if(A[left]==elem) {
A[left] = A[right];
right--;
}else {
left++;
}
}
return left;
}
}