移动零元素
2026/5/6 15:52:27 网站建设 项目流程

移动零元素

给定一个名为 nums 的数字数组,创建一个函数,将数组中的所有零元素移动到数组末尾,同时保持非零元素的原有顺序。
此操作需要在原数组上进行,不能创建原数组的副本。

/** * Move all zeros to the end of the array while maintaining the relative order of non-zero elements. * @param {number[]} nums - The input array. */functionmoveZeroes(nums){// Initialize a pointer to track the position to insert non-zero elementsletinsertPos=0;// Iterate through each element in the arrayfor(leti=0;i<nums.length;i++){// If the current element is not zero, move it to the insert positionif(nums[i]!==0){nums[insertPos]=nums[i];insertPos++;}}// Fill the remaining positions with zerosfor(leti=insertPos;i<nums.length;i++){nums[i]=0;}}module.exports=moveZeroes;

非零依次排列(前移),剩余位置补零。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询