27 Remove Element, 27 removeelement
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.
The requirement of the question is to give an array and a value, delete all elements with the same value in the array and return a new length.
Let's talk about the following ideas:
The double pointer and subscript I loop array can be used. Every time p_last subscript is traversed with I, when A [I] is the same as the given value, p_last is stopped, array length-1, I continues to pass the next value to A [p_last], if it is A [I] and value is different, let p_last + 1
The specific code is as follows:
1 class Solution { 2 public: 3 int removeElement(int A[], int n, int elem) { 4 int length = n; 5 int p_last = 0; 6 for(int i=0;i<n;i++){ 7 A[p_last] = A[i]; 8 if(A[i] == elem) 9 length--;10 else11 p_last++;12 }13 return length;14 }15 };
Or you can have a more intuitive understanding:
The following code:
1 class Solution { 2 public: 3 int removeElement(int A[], int n, int elem) { 4 int length = n; 5 int p_last = 0; 6 for(int i=0;i<n;i++){ 7 if(A[i]==elem){ 8 length--; 9 }else{10 A[p_last] = A[i];11 p_last++;12 }13 }14 return length;15 }16 };
P_last indicates the subscript of the current "new" array, and the I loop array is A [I]! = Elem, assign values, and add p_last plus one "new" to the next element of the array to be inserted. I personally think this method is more intuitive.