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.
public class Solution { public int removeElement(int[] A, int elem) { // Start typing your Java solution below // DO NOT write main() function if(A.length == 0|| A== null) return 0; int length = A.length; int i =0; while(i<length){ if(A[i] == elem){ for(int j = i; j<length-1;j++){ A[j] = A[j+1];} length--; } else{ i++; } } return length; } }
public class Solution { public int removeElement(int[] A, int elem) { // Start typing your Java solution below // DO NOT write main() function if(A.length ==0 || A == null ) return 0; int size = A.length; for(int i = 0; i<size; ){ if(A[i] == elem){ A[i] = A[--size]; } else{ i++; } } return size; } }
Python: class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): index = 0 for i in A: if i != elem: A[index] = i index += 1 return index