File tree 1 file changed +65
-0
lines changed
1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 283. Move Zeroes
2
+
3
+ - Difficulty: Easy.
4
+ - Related Topics: Array, Two Pointers.
5
+ - Similar Questions: Remove Element.
6
+
7
+ ## Problem
8
+
9
+ Given an array ```nums```, write a function to move all ```0```'s to the end of it while maintaining the relative order of the non-zero elements.
10
+
11
+ **Example:**
12
+
13
+ ```
14
+ Input: [0,1,0,3,12]
15
+ Output: [1,3,12,0,0]
16
+ ```
17
+
18
+ **Note**:
19
+
20
+
21
+
22
+ - You must do this **in-place** without making a copy of the array.
23
+
24
+ - Minimize the total number of operations.
25
+
26
+
27
+ ## Solution
28
+
29
+ ```javascript
30
+ /**
31
+ * @param {number[]} nums
32
+ * @return {void} Do not return anything, modify nums in-place instead.
33
+ */
34
+ var moveZeroes = function(nums) {
35
+ var len = nums.length;
36
+ var lastZeroIndex = -1;
37
+ for (var i = 0; i < len; i++) {
38
+ if (nums[i] === 0 && lastZeroIndex === -1) {
39
+ lastZeroIndex = i;
40
+ } else if (nums[i] !== 0 && lastZeroIndex !== -1) {
41
+ swap(nums, i, lastZeroIndex);
42
+ lastZeroIndex += 1;
43
+ }
44
+ }
45
+ };
46
+
47
+ var swap = function(arr, i, j) {
48
+ var tmp = arr[i];
49
+ arr[i] = arr[j];
50
+ arr[j] = tmp;
51
+ };
52
+ ```
53
+
54
+ **Explain:**
55
+
56
+ two pointer: index in the loop and last zero index we met.
57
+
58
+ every time we met a non-zero element, swap it with the last zero element, move the last zero element's index.
59
+
60
+ every time we met a zero element, log it if we haven't met any zero yet, otherwise just move on and do nothing.
61
+
62
+ **Complexity:**
63
+
64
+ * Time complexity : O(n).
65
+ * Space complexity : O(1).
You can’t perform that action at this time.
0 commit comments