Tuesday, September 10, 2013

Remove Element

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.
Solution1: fit for less tartget elements in array
public class Solution {
public int removeElement(int[] A, int elem) {
// Start typing your Java solution below
// DO NOT write main() function
int len=A.length;
for (int i=0; i<len;){
if (A[i]==elem){
A[i]=A[--len];
}
else{
i++;
}
}
return len;
}
}
Solution 2: fit more elemetns in array
class Solution {
public int removeElement(int [] A, int elem){
int newLen=0;
for (int i=0; i<A.length; i++){
if (A[i]!=elem){
A[newLen++]=A[i];
}
}
return newLen;
}
}

No comments:

Post a Comment