【暴刷力扣】283. 移动零

283. 移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

输入: nums = [0,1,0,3,12]

输出: [1,3,12,0,0]

示例 2:

输入: nums = [0]

输出: [0]

提示:

1 <= nums.length <= 104

-231 <= nums[i] <= 231 - 1

进阶:你能尽量减少完成的操作次数吗?

代码

js 复制代码
var moveZeroes = function(nums) {
   let slow = 0, fast = 0
   for (;fast < nums.length; slow++, fast ++) {
    if (nums[slow] === 0) {
        while (nums[fast] === 0) {
            fast ++
        }
        if (nums[fast]) {
            [nums[fast], nums[slow]] = [nums[slow], nums[fast]]
        }
    }
   }
   return nums
};
相关推荐
漫随流水10 小时前
leetcode算法(151.反转字符串中的单词)
数据结构·算法·leetcode
ada7_10 小时前
LeetCode(python)78.子集
开发语言·数据结构·python·算法·leetcode·职场和发展
DeepVis Research10 小时前
【AGI/Simulation】2026年度通用人工智能图灵测试与高频博弈仿真基准索引 (Benchmark Index)
大数据·人工智能·算法·数据集·量化交易
努力学算法的蒟蒻10 小时前
day52(1.3)——leetcode面试经典150
算法·leetcode·面试
leoufung11 小时前
LeetCode 97. 交错字符串 - 二维DP经典题解(C语言实现)
c语言·算法·leetcode
leiming613 小时前
c++ map容器
开发语言·c++·算法
杨校13 小时前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog13 小时前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing201913 小时前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人