Description:
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.
Example:
Input: [0,1,0,3,12]
Output: [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.
题意:给定一个一维数组,包含一定数量的零和非零数,将非零数移动到数组的首部,使零全部位于数组的尾部,并且要求移动后的非零数之间排列顺序保持在移动前的相对顺序;
解法:首先我们要确定的是数组中需要有零,如果没有零就不需要移动了,之后我们要找到数组中的非零数的位置,将非零数与数组首部第一个零交换;一直重复这个操作知道将非零数移动到数组首部;
class Solution {
public void moveZeroes(int[] nums) {
int countZero = 0;
for(int i=0; i<nums.length; i++) {
if (nums[i] == 0) {
countZero++;
}
if (countZero != 0 && nums[i] != 0) {
nums[i - countZero] = nums[i];
nums[i] = 0;
}
}
}
}