问题描述
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.
解决思路
先遍历数组,用count
对所有非0元素进行计数,并且将非0元素保存在nums[count]
的位置,并且count+1。最后将数组剩余长度位置全部置0.
问题解惑
为什么可以将非0元素覆盖在nums[count]
的位置?
因为数组中夹杂着0,所以遇到非0元素,则最多覆盖元素本身;若遇到0,刚好覆盖掉0。
代码
package leetcode;
public class MoveZores {
public void moveZeroes(int[] nums) {
int count = 0;
for (int i:nums){
if (i != 0) {
nums[count] = i;
count++;
}
}
for (int i = nums.length - 1; i >= count ; i--) {
nums[i] = 0;
}
}
}