【Leetcode】283. 移动零(Java版)

给定一个数组 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

**进阶:**你能尽量减少完成的操作次数吗?

带测试版

java 复制代码
/**
 * @description:
 * @author: r1ng
 * @time: 2023/7/31 17:26
 */
public class moveZeroes {
    public static void moveZeroes(int[] nums) {
        //考虑特殊情况
        if(nums == null) return;
        //定义两个数组下标i,j
        for(int i = 0,j =0; i < nums.length;i++){
            if(nums[i] != 0){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j++] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {1,4,0,4,3,8,0,5,3};
        moveZeroes(nums);
        for (int num:nums) {
            System.out.print(num);
        }
    }
}

不带测试版本

java 复制代码
class Solution {
    public void moveZeroes(int[] nums) {
        //考虑特殊情况
        if(nums == null) return;
        //定义两个数组下标i,j
        for(int i = 0,j =0; i < nums.length;i++){
            if(nums[i] != 0){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j++] = temp;
            }
        }
    }
}

b这里我们可以用 0 当做这个中间点,把不等于 0(注意题目没说不能有负数)的放到中间点的左边,等于 0 的放到其右边。 这的中间点就是 0 本身,所以实现起来比快速排序简单很多,我们使用两个指针 i 和 j,只要 numsi!=0,我们就交换 numsi 和 numsj++

相关推荐
地平线开发者2 小时前
J6B vio scenario sample
算法
Flittly10 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了10 小时前
Java 生成二维码解决方案
java·后端
BothSavage14 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn14 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
人活一口气15 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
烬羽16 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
NE_STOP16 小时前
Vibe Coding -- 完整项目案例实操
java
荣码16 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python