当前位置:网站首页>力扣刷题之移动零
力扣刷题之移动零
2022-08-01 18:56:00 【兰舟千帆】
力扣刷题之移动零
这是力扣题中的第283题。
题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。

题目要求将数组中的零移动到数组后面。并且只能在原数组上操作,不可以复制,不可以打乱原来数组元素的顺序。
于是对于中元素的移动的话,如果脑子转动不是很灵光的话,就建议去自己画一个图去试着操作,看看怎么去移动。
你看这些打乱的零怎么移动到后面

将零移动到后面,那就需要将非零元素移动到前面。
一种想法,我们可以用两个指针,然后开始同时初始化指向数组的头部。
然后怎么移动呢?黄色的指针开始移动,移动到3,它不是零,我们将它替换掉白色位置上的0的值。
继续,到这里的时候,我们的黄色指针指向零,我们当然是不会将零前移动的。
这里没有发生移动,白色的指针不要动,黄色的继续移动。
移动到4的时候,然后黄色指向处的数替换白色执行处的值。
然后两个指针继续移动,此时黄色处的值再次替换白色指针处的值,黄色指针到达终点
然后我们白色指针继续移动到终点,并对后面的索引处的值赋0。
这样就移动好了。
我们按照这种逻辑来编写代码
class Solution {
public void moveZeroes(int[] nums) {
int pre01 =0;
for (int pre02 = 0; pre02 < nums.length; pre02++) {
if (nums[pre02]!=0)
{
nums[pre01++]=nums[pre02];
}
}
for (int i = pre01; i < nums.length; i++) {
nums[i]=0;
}
}
}

还有一种方法,在思路上有所区别。这次我们还是初始化两个指针。
只不过这次交换的时候,我们是这样做的。

我们在比较的时候就直接交换。
然后移动,这里两个都是零,不交换。黄色的移动,白色的不变
下一步交换
继续
仔细比较的话,这两种方法存在这区别。我们交换的模式不一样,指针移动到的位置不一样。
来看代码实现。
int pre01 =0;
for (int pre02 = 0; pre02 < nums.length; pre02++) {
if(nums[pre01]==0&&nums[pre02]!=0)
{
int n= nums[pre02];
nums[pre02]=nums[pre01];
nums[pre01++] =n;
}
else if (nums[pre01]!=0)
{
pre01++;
}
}
这样的执行效率不如我们上面的方法高,但是上一种似乎更是像钻空子。
边栏推荐
- [Neural Network] This article will take you to easily analyze the neural network (with an example of spoofing your girlfriend)
- 英国伦敦大学|眼科强化学习:潜在应用和实施挑战
- Leetcode71. 简化路径
- How to use the Golang coroutine scheduler scheduler
- #yyds dry goods inventory# Interview must brush TOP101: the last k nodes in the linked list
- LeetCode 0152. Product Maximum Subarray: dp + Roll in Place
- 安徽建筑大学&杭州电子科技大学|基于机器学习方法的建筑可再生能源优化控制
- Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
- 深入浅出Flask PIN
- How opencv implements image skew correction
猜你喜欢

#yyds dry goods inventory# Interview must brush TOP101: the last k nodes in the linked list

Summer vacation second week wrap-up blog

GZIPOutputStream 类源码分析

el-form-item prop属性动态绑定不生效如何解决

XML配置

在Map传值与对象传值中模糊查询

Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读

opencv syntax Mat type summary

在全志V853开发板试编译QT测试

odoo coding conventions (programming conventions, coding guidelines)
随机推荐
ExcelPatternTool: Excel表格-数据库互导工具
无需破解,官网安装Visual Studio 2013社区版
No need to crack, install Visual Studio 2013 Community Edition on the official website
Leetcode73. 矩阵置零
Detailed explanation of DBPack SQL Tracing function and data encryption function
MySQL数据库————流程控制
Shell script topic (07): file from cfs to bos
Leetcode74. 搜索二维矩阵
LeetCode 0151. Reverse a string of words
Screenshot of Selenium in Remote
MLX90640 红外热成像仪测温模块开发笔记(完整篇)
123123123123
C#/VB.NET:从 PDF 文档中提取所有表格
How to solve the dynamic binding of el-form-item prop attribute does not take effect
云原生全景图详解
【翻译】CNCF培养的OpenMetrics成为一个孵化项目
opencv如何实现图像倾斜校正
在全志V853开发板试编译QT测试
腾讯云主机安全 x 轻量应用服务器|强强联合主机安全普惠版重磅发布
Go GORM transaction instance analysis