[LintCode] Move Zeroes 移动零
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.
Notice
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
Example
Given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
LeetCode上的原题,请参见我之前的博客Move Zeroes。
解法一:
class Solution { public: /** * @param nums an integer array * @return nothing, do this in-place */ void moveZeroes(vector<int>& nums) { for (int i = 0, j = 0; i < nums.size(); ++i) { if (nums[i]) { swap(nums[i], nums[j++]); } } } };
解法二:
class Solution { public: /** * @param nums an integer array * @return nothing, do this in-place */ void moveZeroes(vector<int>& nums) { int left = 0, right = 0; while (right < nums.size()) { if (nums[right]) { swap(nums[left++], nums[right]); } ++right; } } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 如何统计不同电话号码的个数?—位图法
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 用c#从头写一个AI agent,实现企业内部自然语言数据统计分析
· 三维装箱问题(3D Bin Packing Problem, 3D-BPP)
· Windows上,10分钟构建一个本地知识库
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 使用 AOT 编译保护 .NET 核心逻辑,同时支持第三方扩展