当前位置:网站首页>LeetCode每日两题01:移动零 (均1200道)方法:双指针
LeetCode每日两题01:移动零 (均1200道)方法:双指针
2022-08-10 01:54:00 【那人独钓寒江雪.】
题目如下:
解题思路:使用双指针,左指针指向当前已经处理好的序列的尾部,右指针指向待处理序列的头部。右指针不断向右移动,每次右指针指向非零数,则将左右指针对应的数交换,同时左指针右移。
class Solution {
public int moveZeroes(int[] nums) {
//左指针左边均为非零数 右指针左边直到左指针处均为零
int n=nums.length, left=0,right=0;
while (right<n){
//0<7
if (nums[right]!=0){
swap(nums,left,right);
left++;
}
right++;
}
}
public void swap(int[] nums,int left,int right){
int temp=nums[left];
nums[right]=nums[left];
nums[left]=temp;
}
}

优化方法:
解题思路:我们创建两个指针i和j,第一次遍历的时候指针j用来记录当前有多少非0元素。即遍历的时候每遇到一个非0元素就将其往数组左边挪,第一次遍历完后,j指针的下标就指向了最后一个非0元素下标。第二次遍历的时候,起始位置就从j开始到结束,将剩下的这段区域内的元素全部置为0。
class Solution {
public void moveZeroes(int[] nums) {
if(nums==null) {
return;
}
//第一次遍历的时候,j指针记录非0的个数,只要是非0的统统都赋给nums[j]
int j = 0;
for(int i=0;i<nums.length;++i) {
if(nums[i]!=0) {
nums[j++] = nums[i];
}
}
//非0元素统计完了,剩下的都是0了
//所以第二次遍历把末尾的元素都赋为0即可
for(int i=j;i<nums.length;++i) {
nums[i] = 0;
}
}
}

边栏推荐
猜你喜欢
随机推荐
STM32F103驱动HCSR04超声波测距显示
RESOURCE_EXHAUSTED: etcdserver: mvcc: database space exceeded
sql实战积累
数据库治理利器:动态读写分离
【机器学习】随机森林、AdaBoost、GBDT、XGBoost从零开始理解
【UNR #6 C】稳健型选手(分治)(主席树)(二分)
Database management tool: dynamic read-write separation
odoo公用变量或数组的使用
【论文笔记】基于深度学习的机器人抓取虚拟仿真实验教学系统
【UNR #6 B】机器人表演(DP)
Janus actual production case
openpose脚部标注问题梳理
one of the variables needed for gradient computation has been modified by an inplace
Chip Information|Semiconductor revenue growth expected to slow to 7%, Bluetooth chip demand still growing steadily
[Syntax sugar] About the mapping of category strings to category numeric ids
Fusion Compute网络虚拟化
Premint工具,作为普通人我们需要了解哪些内容?
【每日一题】1413. 逐步求和得到正数的最小值
深度学习(五) CNN卷积神经网络
力扣每日一题-第51天-744. 寻找比目标字母大的最小字母






![[网鼎杯 2020 青龙组]AreUSerialz](/img/33/a237185ffe0c5780432c242c36cbdc.png)


