每日一leetcode:移动零

目录

解题过程:

描述:

分析条件:

解题思路:

通过这道题可以学到什么:


解题过程:

描述:

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

示例 1:

复制代码
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

示例 2:

复制代码
输入: nums = [0]
输出: [0]

提示

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

分析条件:

第一遍的思路:(错误思路)

当数组的长度为1时,直接返回这个数组

当数组的长度大于1时,我们从数组的第一个数开始遍历,遇到0,交换

比如 1 0 2 0 3 我们就把它变成 1 2 0 3 0 把遇到的第一个0交换到末尾

java 复制代码
class Solution {
    public void moveZeroes(int[] nums) {
        if(nums.length == 1){
            return;
        }   
        // 0 1 0 3 12
        for(int i = 0;i < nums.length;i++){
            if(nums[i] != 0){
                continue;
            }
            for(int j = i;j < nums.length - 1;j++){
                int temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
            }
        }
    }
}

这种写法只通过了28/75个用例,原因是 0,0,1 如果0连续,那么这种逻辑会漏掉一些0

正确解题思路:

java 复制代码
class Solution {
    public void moveZeroes(int[] nums) { 1 1 0 
        //1 2 0 3 12
        int n = nums.length;
        //left为左指针,left索引左边的数均为已处理数
        int left = 0;
        //rigth为右指针,right索引不断右移寻找非0数
        int right = 0;
        while(right < n){
//(nums[right] != 0时再交换,这段逻辑可以保证left和right一起移动到第一个num[n] = 0处,
//此时left = n,right = n,下一步left = n,right = n + 1,right开始寻找非0数
            if(nums[right] != 0){
                int temp = nums[right];
                nums[right] = nums[left];
                nums[left] = temp;
                left++;
            }
            right++;
        }
    }
}

通过这道题可以学到什么:

1.数组的长度,nums.length 后面不加()!

2.while循环中,我们要用numsright != 0作为条件,这样可以带着left和right一起移动到数组中第一个0处

相关推荐
武子康2 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw058 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术9 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs10 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575910 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI1 天前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi1 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M1 天前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen1 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#