LeetCode 283. Move Zeroes

本文介绍了一种在原地将数组中所有零元素移动到数组末尾同时保持非零元素相对顺序的方法。通过两种不同的双指针技术实现,确保了最小的操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
分析:本题不能新建一个数组来辅助排序,首先想到的便是双指针遍历排序数组。
代码:
public class Solution {
    public void moveZeroes(int[] nums) {
        for(int i = 0;i < nums.length;i++){
            if(nums[i] == 0){
                for(int j = i + 1;j < nums.length;j++){
                    if(nums[j] != 0){
                        nums[i] = nums[j];
                        nums[j] = 0;
                        break;
                    }
                }
            }
        }
    }
}
代码注释:1.先定义指针i,2.用指针i来遍历数组,当找到数组中第一个值为0的时候,启用第二个指针j;3.指针j从指针i的下一个值开始遍历,找到第一个不为零的值赋值给指针i指向的数,然后将指针j指向的数置零。4.依次遍历数组中所有数据,得到正确结果。
双指针的另一种表示形式为:
public class Solution {
    public void moveZeroes(int[] nums) {
        // for(int i = 0;i < nums.length;i++){
        //     if(nums[i] == 0){
        //         for(int j = i + 1;j < nums.length;j++){
        //             if(nums[j] != 0){
        //                 nums[i] = nums[j];
        //                 nums[j] = 0;
        //                 break;
        //             }
        //         }
        //     }
        // }
        int i = 0;
        int j = 0;
        while(i < nums.length){
            if(nums[i] == 0 || i == j){
                i++;
            }else{
                if(nums[j] == 0){
                    nums[j] = nums[i];
                    nums[i] = 0;
                    i++;
                }
                j++;
            }
        }
        
    }
}

代码注释:1.先定义两个指针都指向数组的首位,2.取指针i对数组进行遍历,如果和j指向不同数据且i指向的数据不为0时,此时如果j指向的数据不为零,则将i指向的数据赋值给j指针的位置,将i指针的数据置零;如果j指向0,则j++.
图解:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值