Given the nums an array, a write function to all moved to the end of the array 0, while maintaining the relative order of nonzero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Description:
Must be operated on the original array, you can not copy additional array.
Minimize the number of operations.
Method: double pointer
i 0 points to the first;
j points to the first non-zero;
0 will move step by step to the right, one by one each treatment 0
. 1 class Solution { 2 public : . 3 void moveZeroes (Vector < int > & the nums) { . 4 int I = 0 , J = 0 ; . 5 for (; J <nums.size (); J ++ ) . 6 { . 7 the while (I < nums.size () && the nums [I] =! 0 ) I ++; // until the first 0, i is stopped . 8 the while (J <nums.size () && the nums [J] == 0 ) J ++; // is equal to 0, after the exchange is the position, so the time k ++, with continued to find a non-0 . 9 IF (nums.size J == ()) BREAK ; 10 the else IF (I> J) Continue ; . 11 the else { // do the exchange, they must be. 1 = J + I 12 is int tmp = the nums [J]; 13 is the nums [J] = the nums [I]; 14 the nums [ i] = tmp; // this time point i is non-zero after the switching, j points to the exchange over 0 15 i ++; // decrease a while, a bit save memory 16 } 17 } 18 }
. 1 class Solution { 2 public : . 3 void moveZeroes (Vector < int > & the nums) { . 4 int I = 0 ; . 5 for ( int J = 0 ; J <nums.size (); J ++) { // J encountered 0 when, at this time as the last round i ++, so this is actually encountered this time i a 0 . 6 IF (the nums [J] =! 0 ) { . 7 the nums [i] = the nums [J]; . 8 i ++ ; . 9 } 10 } 11 //This time point i is either 0 or i previously assigned non-zero, then after switching, i refers to 0; i refers to the short time that is 0 12 is the while (i < nums.size ()) { 13 is the nums [I ++] = 0 ; 14 } 15 16 } . 17 };