283. Move Zeroes
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.
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
My Solutions:
extra-place的解法是Time: O(n); Space: O(n)
in-place 解法:用一个pointer记录截止此处之前,全部数字都是已经替换成非0数字的index。然后再iterate一遍,把pointer之后到array结尾之前的数字变成0。
public void moveZeroes(int[] nums) {
int len = nums.length;
int pointer = 0;
for (int i = 0; i < len; i++) {
if (nums[i] != 0) {
nums[pointer] = nums[i];
pointer++;
}
}
while (pointer != len) {
nums[pointer] = 0;
pointer++;
}
}
Last updated