/*****************************************************问题描述*************************************************
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.
给定一个数值数组,将数组中的0移动到数组最后,其他元素相对顺序不变
/*****************************************************我的解答*************************************************
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
var length = nums.length;
var count = 0;
for(var index = 0; count < length;)
{
if(nums[index] == 0)
{
nums.splice(index, 1);
nums.push(0);
}
else
{
index++
}
count++;
}
};
leetCode刷题记录41_283_Move Zeroes
最新推荐文章于 2026-04-01 15:12:35 发布
本文介绍了一种在不复制数组的情况下,将所有零元素移至数组末尾同时保持非零元素相对顺序的算法。通过具体示例[0,1,0,3,12]展示了算法实现过程,最终输出为[1,3,12,0,0]。该算法注重减少操作次数,提升效率。
2万+

被折叠的 条评论
为什么被折叠?



