移动零

/*
leetCode -- 移动零
 */
public class Remove_zero {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] number = new int[]{1, 2, 0, 9, 9, 0, 2, 1,5,4,3,2,32,0,32,32,434,0,3};
        solution.moveZeroes(number);
    }
}



上面是测试:
//----------------------------------------
下面是分装的"移除零"的方法:



/**
 * 输入: nums = [0,1,0,3,12]
 * 输出: [1,3,12,0,0]
 * <p>
 * 输入: nums = [0]
 * 输出: [0]
 */
class Solution {
    public void moveZeroes(int[] nums) {
        if (nums.length == 0 || nums == null) {
            return;
        }
        int[] temp = new int[nums.length];
        int t = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                temp[t] = nums[i];
                t++;
            }
        }
        int number = 0;
        for (int i : temp) {
            if (i == 0) {
                number++;
            }
        }
        for (int w = 0; w < temp.length - 1 - number; w++) {
            for (int i = 0; i < temp.length - 1 - w - number; i++) {
                if (temp[i] > temp[i + 1]) {
                    int exchange = temp[i];
                    temp[i] = temp[i + 1];
                    temp[i + 1] = exchange;
                }
            }
        }
        System.out.println(Arrays.toString(temp));
    }
}

解析:

用n和t两个指针,来移动,所谓的"指针"就是定义出来的一个数,在循环中跳动,和++的操作

依次用两个指针,把满足不等于0的nums值,赋给tmp上。

posted on 2022-07-20 11:51  陈嘻嘻-  阅读(71)  评论(0编辑  收藏  举报

导航