The idea is to loop the Array, and swap/replace the swap candidate index to next good index. Both will work.
public class Solution {
public int removeElement(int[] A, int elem) {
if(A == null || A.length == 0){
return 0;
}
int begin = 0;
int end = A.length - 1;
while(begin <= end){
if(A[end] == elem){
end--;
continue;
}
if(A[begin] == elem){
A[begin] = A[end];
A[end] = elem;
}
begin++;
}
return end + 1;
// int index = 0;
// int swapIndex = -1;
// int res = A.length;
// while(index < A.length){
// if(A[index] == elem){
// res--;
// if(swapIndex == -1){
// swapIndex = index;
// }
// }else{
// if(swapIndex != -1){
// A[swapIndex] = A[index];
// //A[index] = elem;
// swapIndex++;
// }
// }
// index++;
// }
// return res;
}
}
没有评论:
发表评论