"027-remove element (removes elements from an array)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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.
Main Topic
Given an array and a value, delete the element in the array equal to this value, and return the new length with this array.
Thinking of solving problems
Find the position of the element with the value Elem from the left, J find the position of the element that is not elem from the right, and then move the value of the J position to the I position.
Code Implementation
Algorithm implementation class
Public classSolution { Public int removeelement(int[] A,intElem) {intExchange =0;number of records exchanged, that is, the number of values equal to the Elem element in the statistical array //Algorithm idea: I find the position of the element with value Elem from the left, J to find the position of the element not elem from the right, The equals sign is to allow an array of length 1 to enter for(inti =0, j = a.length-1; I <= J; i++) {if(A[i] = = elem) {//Find the element to swapexchange++; while(J > I && a[j] = = elem) {//Start looking forward from the back of the array to the first element not equal to Elemexchange++;//The element with value Elem is explained to be exchanged, but the exchange process can savej--; }//Case 1: to the position of the element not elem, place the element of J position in the I position //Case 2: No elem element is found, that is, all element values after I are E, at which point there is j=i //In either case, putting the value of J into I is not a matter ofA[i] = A[j]; j--;//J has been swapped for use so also to move to a new position with the front} }returnA.length-exchange; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47052643"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "027-remove element (deletes the specified elements in the array)"