LeetCode——第283题:移动0

本文介绍了一种算法,用于将数组中的所有零元素移至数组末尾,同时保持非零元素的相对顺序不变。提供了三种不同的实现方法,并附带示例代码。

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

题目:

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

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

代码:
package leetCode;

/**
 * 2018.7.19 移动0
 * 
 * @author dhc
 *
 */
public class TwoHundredsAndEightThree {

    //循环数组,依次将不等于0的数向前移动
    //待改进(75ms)
    //采用的是移动元素
    public static void moveZeroes1(int[] nums) {
        for(int i = 0;i < nums.length;i++) {
            if(nums[i] != 0) {
                for(int j = i;j > 0;j--) {
                    //因为如果不等于0,其之前的数也不存在等于0的数
                    if(nums[j - 1] == 0) {
                        int tem = nums[j];
                        nums[j] = nums[j - 1];
                        nums[j - 1] = tem;
                    }
                }
            }
        }
    }
    //大佬方法(插入法,类似于排序的插入操作)
    public static void moveZeroes2(int[] nums) {
        int index = 0;
        for(int i = 0;i<nums.length;i++) {
            if(nums[i] != 0) {
                nums[index++] = nums[i]; 
            }
        }
        //补全后面的0
        for(int i = index;i<nums.length;i++) {
            nums[i] = 0;
        }
    }
    //第一遍,没注意到需要保证非0元素的相对位置
        public static void moveZeroes(int[] nums) {
            int i = 0;
            int j = nums.length-1;
            while(i<j) {
                while(i<nums.length) {
                    i++;
                    if(nums[i-1] == 0) {
                        break;
                    }
                }
                while(j>0) {
                    j--;
                    if(nums[j+1] != 0) {
                        break;
                    }
                }
                if(i < j) {
                    int tem = nums[i-1];
                    nums[i-1] = nums[j+1];
                    nums[j+1] = tem;
                }
            }
        }
    public static void main(String[] args) {
        int[] nums = new int[] {0,0,1};
        moveZeroes2(nums);
        for (int z = 0; z < nums.length; z++) {
            System.out.print(nums[z]+" ");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值