Move Zeroes
Description
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.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Solution(javascript)
/*
* @lc app=leetcode id=283 lang=javascript
*
* [283] Move Zeroes
*/
// @lc code=start
// /** 1: O(N)
// * @param {number[]} nums
// * @return {void} Do not return anything, modify nums in-place instead.
// */
// const moveZeroes = function (nums) {
// let right = 0
// for (let i = 0; i < nums.length; i++) {
// if (nums[i] === 0) {
// right = Math.max(i + 1, right + 1)
// while (nums[right] === 0 && right < nums.length) {
// right++
// }
// if (right < nums.length) {
// nums[i] = nums[right]
// nums[right] = 0
// } else {
// break
// }
// }
// }
// }
/** 2: O(N)
* 把不是 0 的元素往前移动
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
const moveZeroes = function (nums) {
let index = 0
for (const num of nums) {
if (num !== 0) {
nums[index++] = num
}
}
while (index < nums.length) {
nums[index++] = 0
}
}
// @lc code=end