public class Solution {
public int removeElement(int[] A, int elem) {
int m = 0;
for(int i = 0; i < A.length; i++){
if(A[i] != elem){
A[m] = A[i];
m++;
}
}
return m;
}
}
public int removeElement(int[] A, int elem)
{
LinkedList<Integer> list = new LinkedList<Integer>();
if(A.length ==0 )
return 0;
for(int i=0;i<A.length;i++)
{
list.add(A[i]);
}
Iterator<Integer> it = list.iterator();
try
{
while(it.hasNext())
{
if(it.next() == elem)
{
it.remove();
}
}
}
catch(Exception e)
{
System.out.println("No such element");
}
return list.size();
}
Thanks for your idea @vy7Sun. I tried for a clean version.
class Solution {
public int removeElement(int[] nums, int val) {
if(nums==null || nums.length==0) return 0;
int len = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] != val){int tmp = nums[len]; nums[len++] = nums[i]; nums[i] = tmp;}
}
return len;
}
}