11// Source : https://leetcode.com/problems/move-zeroes/
2- // Author : Calinescu Valentin
2+ // Author : Calinescu Valentin, Hao Chen
33// Date : 2015-10-21
44
55/* **************************************************************************************
2121
2222
2323
24- /*
25- * Solutions
26- * =========
27- *
28- * One solution would be to store the position of the next non-zero element of the array.
29- * Every position of the array, starting with position 0, must store this next non-zero
30- * element until we can no more do that, case in which we need to add the remaining zeros
31- * that we skipped.
32- *
33- *
34- * Time Complexity: O(N)
35- * Space Complexity: O(1)
36- *
37- */
3824class Solution {
3925public:
26+ /*
27+ * Solution (Calinescu Valentin)
28+ * ==============================
29+ *
30+ * One solution would be to store the position of the next non-zero element of the array.
31+ * Every position of the array, starting with position 0, must store this next non-zero
32+ * element until we can no more do that, case in which we need to add the remaining zeros
33+ * that we skipped.
34+ *
35+ *
36+ * Time Complexity: O(N)
37+ * Space Complexity: O(1)
38+ *
39+ */
4040 void moveZeroes (vector<int >& nums) {
4141 int i = 0 , poz = 0 ;
4242 for (i = 0 ; i < nums.size () && poz < nums.size (); i++)
@@ -52,4 +52,35 @@ class Solution {
5252 for (; i < nums.size (); i++)
5353 nums[i] = 0 ;
5454 }
55+
56+
57+
58+ /*
59+ * Another implemtation which is easy to understand (Hao Chen)
60+ * ===========================================================
61+ *
62+ * We have two pointers to travel the array, assume they named `p1` and `p2`.
63+ *
64+ * 1) `p1` points the tail of current arrays without any ZEROs.
65+ * 2) `p2` points the head of the reset array which skips the ZEROs.
66+ *
67+ * Then we can just simply move the item from `p2` to `p1`.
68+ *
69+ */
70+ void moveZeroes (vector<int >& nums) {
71+ int p1=0 , p2=0 ;
72+
73+ // Find the first ZERO, where is the tail of the array.
74+ // (Notes: we can simply remove this!)
75+ for (; nums[p1]!=0 && p1<nums.size (); p1++);
76+
77+ // copy the item from p2 to p1, and skip the ZERO
78+ for (p2=p1; p2<nums.size (); p2++) {
79+ if ( nums[p2] == 0 ) continue ;
80+ nums[p1++] = nums[p2];
81+ }
82+
83+ while ( p1<nums.size () ) nums[p1++] = 0 ;
84+ }
85+
5586};
0 commit comments