Delete ElementGiven an array and a value, delete the same number as the value in situ, returning the length of the new array.
The order of the elements can be changed and will have no effect on the new array.
Sample Example
Gives an array [0,4,4,0,0,2,4,4], and a value of 4
Returns a new array of 4 and 4 elements for [0,0,0,2]
The idea is to move elements except the deleted element to the leftmost, R is the right-most non-deleted element, and the right-most non-deleted element can be found at the beginning. Use I to iterate through the array, find the leftmost element, and assign the element r to position I. In the code, I first find the leftmost element, and then find the right-most non-deleted element. Time complexity is the same.
1 Public classSolution {2 /** 3 *@parama:a List of integers4 *@paramElem:an integer5 *@return: The new length after remove6 */7 Public intRemoveelement (int[] A,intelem) {8 intr = A.length-1;9 if(R < 0)return0;Ten inti = 0; One A while(R >i) { - if(A[i] = =elem) { - while(A[r] = = Elem && r > 0) r--; the if(R >i) { -A[i] =A[r]; -r--; - } + } -i++; + } A at if(A[r] = = elem) r--; - - returnR + 1; - } -}View Code
Delete Element (Lintcode)