Skip to content

Commit ffe6af8

Browse files
committed
feat: Solving "Move zeroes" (LeetCode | #283 | Easy)
1 parent 45f5fb1 commit ffe6af8

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

sliding-window/max-avg-subarray.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,4 @@ function findMaxAverage(nums, k) {
3737
}
3838

3939
return maxAvg;
40-
};
41-
40+
}

two-pointers/move-zeroes.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* LeetCode | #283 | Easy
3+
*
4+
* Given an integer array nums, move all 0's to the end of it while maintaining the
5+
* relative order of the non-zero elements.
6+
*
7+
* Note that you must do this in-place without making a copy of the array.
8+
*
9+
* Constraints:
10+
* 1. 1 <= nums.length <= 10^4
11+
* 2. -2^31 <= nums[i] <= 2^31 - 1
12+
*
13+
*/
14+
15+
/**
16+
* Time complexity: O(n) - Space complexity: O(1)
17+
*
18+
* @param {number[]} nums
19+
* @return {void} Do not return anything, modify nums in-place instead.
20+
*/
21+
function moveZeroes(nums) {
22+
if (nums.length < 2) {
23+
return;
24+
}
25+
26+
let i = 0;
27+
let j = 0;
28+
while (j < nums.length) {
29+
if (nums[i] !== 0) {
30+
i++;
31+
32+
if (j <= i) {
33+
j++;
34+
}
35+
} else if (nums[j] !== 0) {
36+
nums[i] = nums[j];
37+
nums[j] = 0;
38+
} else {
39+
j++;
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)