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 are you leave beyond the new length.
The requirement of the topic is this, the initial idea is very simple, first with a variable length of the array A, followed by an element in a traversal comparison, if the elements in a and ele the same, then the length minus 1
int length = a.length; for (int i = 0;i<a.length;i++) { if(a[i] = = elem) {= Length-1; } } return length;
After the submission of the error, I think the main reason is not to change the original array, only for the length of the array changes.
After modification:
public class solution { int removeelement (int [] A, int Span style= "color: #000000;" > Elem) { int length = 0< span> for (int i = 0;i<a.length;i++< Span style= "color: #000000;" ) { if (A[i]!= Elem) { A[length] = A[i]; Length = length + 1; }} return length; }}
Submitted successfully, then saw the online look at other people's methods, most people are if encountered Elem, it is adjusted to the back of the array,
Public classSolution { Public intRemoveelement (int[] A,intelem) { intLength =a.length; for(inti = 0;i<length;i++){ if(A[i] = =elem) {A[i]= A[length-1]; I--; Length--; } } returnlength; }}
Think of it I and length processing there very well, take it for reference.
Remove Element of Leetcode