当前位置:网站首页>力扣刷题之移动零
力扣刷题之移动零
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++;
}
}
这样的执行效率不如我们上面的方法高,但是上一种似乎更是像钻空子。
边栏推荐
- When compiling a program with boost library with VS2013, it prompts fatal error C1001: An internal error occurred in the compiler
- 驱动上下游高效协同,跨境B2B电商平台如何释放LED产业供应链核心价值?
- 电商库存系统的防超卖和高并发扣减方案
- Friends who want to use the database anytime, anywhere and as you like, all attention!
- Leetcode75. Color Classification
- [National Programming] "Software Programming - Lecture Video" [Zero Basic Introduction to Practical Application]
- MySQL database - stored procedures and functions
- JVM运行时数据区与JMM内存模型是什么
- 网站建设流程
- Keras深度学习实战——交通标志识别
猜你喜欢

MySQL数据库————流程控制

Shell script topic (07): file from cfs to bos
Detailed explanation of DBPack SQL Tracing function and data encryption function

Keras深度学习实战——交通标志识别

Become a Contributor in 30 minutes | How to participate in OpenHarmony's open source contributions in multiple ways?

Leetcode73. 矩阵置零

Redis的内存淘汰策略和过期删除策略的区别是什么

PanGu-Coder:函数级的代码生成模型

Prometheus的Recording rules实践

How many steps does it take to convert an ENS domain name into music?
随机推荐
C#/VB.NET 从PDF中提取表格
请你说说多线程
金鱼哥RHCA回忆录:CL210管理OPENSTACK网络--章节实验
无需破解,官网安装Visual Studio 2013社区版
How to use the Golang coroutine scheduler scheduler
硬件大熊原创合集(2022/07更新)
kubernetes-部署nfs存储类
Summer vacation second week wrap-up blog
Leetcode71. Simplified Paths
金鱼哥RHCA回忆录:CL210管理OPENSTACK网络--网络配置选项
2022,程序员应该如何找工作
Leetcode72. Edit Distance
MySQL数据库————流程控制
【LeetCode】Day109-最长回文串
Three solutions: npm WARN config global --global, --local are deprecated. Use --location=global instead.
1065 A+B and C (64bit)
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
What is the implementation principle of Go iota keyword and enumeration type
明尼苏达大学团队结合高通量实验与机器学习,实现有效可预测的特定位点重组过程,可调节基因编辑速度
【翻译】CNCF培养的OpenMetrics成为一个孵化项目