题目链接:https://leetcode.com/problems/move-zeroes/
题目:
nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
- You must do this in-place
- Minimize the total number of operations.
思路:
记录0的数目n,然后将数组最后n个数置0。实质是删除操作,参见
算法:
public void moveZeroes(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
count++;
} else {
nums[i - count] = nums[i];
}
}
for (int j = 0; j < count; j++) {
nums[nums.length - 1 - j] = 0;
}
}