forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0283-move-zeroes.js
46 lines (38 loc) · 1005 Bytes
/
0283-move-zeroes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Two Pointer
* Time O(N) | Space O(N)
* https://leetcode.com/problems/move-zeroes/
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
const arr = new Array(nums.length).fill(0);
let [left, right] = [0, 0];
while (right < nums.length) {
const isZero = (nums[right] === 0);
if (!isZero) {
arr[left] = nums[right];
left++;
}
right++;
}
return arr;
};
/**
* 2 Pointer
* Time O(N) | Space O(1)
* https://leetcode.com/problems/move-zeroes/
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = (nums) => {
let [ left, right ] = [ 0, 0 ];
while (right < nums.length) {
const canSwap = (nums[right] !== 0)
if (canSwap) {
[nums[left], nums[right]] = [nums[right], nums[left]];
left++;
}
right++;
}
};