Java编程题目-14:MoveZeroes

题目要求:
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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
原题链接:请戳这里
给你一个数组,写一个方法将所有的0移动到数组末尾,同时保持数组原有的非零元素之间的顺序关系。

下面是我的代码:

public void MoveZeroes(int[] nums) {
        int zero_num = 0;
        for (int num : nums) {
            if (num == 0)
                zero_num++;// 循环遍历数组,计算数组中“0”的个数
        }
        int len = nums.length;
        int temp = 0;
        for (int i = 0; i < len; i++) {
            if (nums[i] == 0) {// 循环遍历数组,找到“0”就将其移动到数组最后一位。
                for (int j = i; j < len - 1; j++) {
                    temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
                i--;// *移动后之前的元素index都会向前加了一个,所以i后退一次
                if (i == len - zero_num - 1)// 当末尾全是“0”的时候就退出循环
                    break;
            } else {
                continue;
            }
        }
    }

程序写的感觉比较麻烦,但是有几点是必须要注意的:

  1. 数组中零的个数,这个决定了退出便利循环的条件;
  2. 每次从数组中遍历得到一个零后,下次遍历要后退一个,不然会出现遗漏“0”的情况。比如:[1,2,0,0,4],当i=2的时候,将“0”移至末尾,得到[1,2,0,4,0],不后退的话,直接i++,得到i=3,即元素4进行处理了,漏掉了第二个0;
  3. 代码中星号位置比较关键,就是退出循环的条件和时机,当数组下表循环到除去零的个数时,则退出循环,不然后面就是死循环了。

下面是高手写的代码~请欣赏:

public void moveZeroes(int[] nums){
            int index=0;
            for (int i=0;i<nums.length;i++){
                if (nums[i]!=0) nums[index++]=nums[i];//*
            }
            while(index<nums.length){
                nums[index++]=0;
            }
        }
  1. 首先循环遍历数组,将数组中非零的元素一次赋值到数组前端。index使用的太好了!
  2. 再将数组末尾除去非零元素都赋值为0
  3. 太简洁了!羡慕!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值