[LeetCode] 283. Move Zeroes
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
移动零。
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
思路
题意很直观,将数组中所有 0 移动到数组的末端。要求不能使用额外空间。
思路是给一个 cur 指针和一个 i 指针,用 i 去遍历数组。当数组遇到非 0 的数字的时候,就放到 cur 的位置,cur++。如果扫描完整个数组 cur 的位置没有到达数组末尾,后面的位置用 0 补齐。
复杂度
时间O(n)
空间O(1)
代码
Java实现
class Solution { public void moveZeroes(int[] nums) { int cur = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { nums[cur] = nums[i]; cur++; } } while (cur < nums.length) { nums[cur] = 0; cur++; } } }
JavaScript实现
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function (nums) { let cur = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { nums[cur] = nums[i]; cur++; } } while (cur < nums.length) { nums[cur] = 0; cur++; } };
相关题目
283. Move Zeroes 2460. Apply Operations to an Array
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类