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]
.
==================================我是华丽的分隔符,我上面是题目,下面是代码==================================
以下算法的主要逻辑是:
一、将数组中为“0”的取出
二、将“0”后面的数向前移一位
三、一共有几个“0”,就在数组后面加几个“0”
public class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != 0) {
nums[i] = nums[j];
i++;
}
}
for (int k = i; k < nums.length; k++) {
nums[k] = 0;
}
}
}