leetcode原地删除系列-283移除0
/**
<p>给定一个数组 <code>nums</code>,编写一个函数将所有 <code>0</code> 移动到数组的末尾,同时保持非零元素的相对顺序。</p>
<p><strong>请注意</strong> ,必须在不复制数组的情况下原地对数组进行操作。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> nums = <code>[0,1,0,3,12]</code>
<strong>输出:</strong> <code>[1,3,12,0,0]</code>
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> nums = <code>[0]</code>
<strong>输出:</strong> <code>[0]</code></pre>
<p> </p>
<p><strong>提示</strong>:</p>
<meta charset="UTF-8" />
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<p><b>进阶:</b>你能尽量减少完成的操作次数吗?</p>
<div><div>Related Topics</div><div><li>数组</li><li>双指针</li></div></div><br><div><li>👍 1525</li><li>👎 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public void moveZeroes(int[] nums) {
if(nums.length==0){
return ;
}
int fast=0,slow=0;
for (int i = 0; i < nums.length; i++) {
if(nums[fast]!=0){
nums[slow]=nums[fast];
slow++;
}
fast++;
}
for (int i = slow; i <nums.length ; i++) {
nums[i]=0;
}
return;
}
}
//leetcode submit region end(Prohibit modification and deletion)
不恋尘世浮华,不写红尘纷扰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理