Problem Description:
Givenan array and a value, remove all instances of the, value in place and returnthe new length.
The order of elements can be changed. It doesn ' tmatter what are you leave beyond the new length.
Problem Analysis:
The key to this algorithm is the movement of the elements of the array, which is optimized by the poor performance of the method of moving forward through all elements behind the array when a A[i]==elem is encountered.
Method One: The double pointer method, when the element at start needs to be removed, is populated with the end element
But note that the end element is also Elem, so after exchanging the start and end elements, note that start does not increment
Method Two: Count the currently traversed I -length array, the number of Elem that need to be removed removecount, you can move A[i] to a[i- Removecount] Place,
This method is better than the previous method, the time complexity depends on the number of Elem , if the number of elements to be removed more, then this method is better; otherwise, the method is superior
Code:
/* Method One: Double pointer method, when the element at start needs to be removed, use the end element to fill but note that the end element is also elem, so after swapping the start and end elements, note that start does not increment */public class Solution { public int removeelement (int[] A, int elem) { if (A = = NULL | | A.length = = 0) return 0;int start = 0;int end = A.length-1;while (Start < end) {//The key to the problem is moving the elements in the array if (a[start] = = elem) a[s Tart] = a[end--];elsestart++;} return A[start] = = Elem? Start:start + 1; }}
/* Method Two: Statistics the currently traversed I-length array, need to remove the number of Elem Removecount, you can move A[i] to A[i-removecount], This method than the previous method, the complexity of time depends on the number of Elem, This method is better if the number of elements to be removed is greater; otherwise, the method is better */public class solution {public int removeelement (int[] A, int elem) { int Removecount = 0; for (int i = 0; i < a.length; i++) { if (a[i] = = elem) removecount++; else A[i-removecount] = A[i]; } return a.length-removecount; } }
Leetcode-27 Remove Element