leetcode algorithm question-moving zero Java

To solve this problem, we can create a new array of equal length. After initialization, the elements in the array are all zero. We only need to traverse the original array and transfer the data that is not 0 to the new array. The following is the code accomplish:

public static void main(String[] args) {
    System.out.println("移动零:" + Arrays.toString(moveZero(new int[]{0,1,0,3,12})));
}
//移动零
    public static int[] moveZero(int[] nums) {
        int[] arr = new int[nums.length];
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                arr[j++] = nums[i];
            }
        }
        return arr;
    }

Moving zeros: [1, 3, 12, 0, 0]

おすすめ

転載: blog.csdn.net/wfdfg/article/details/133324149