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]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
題意即,給出一個整數數組,把其中的0都移動到數組的末尾,同時保持原來數組中其他非零元素的相對順序,並且要求不能重新申請另外的數組空間,要求最小化要進行操作的元素數量。
解題思路:遍歷數組,使用一個索引進行非零元素的插入操作,最後將剩下的全部元素全部賦值爲0。時間複雜度爲O(n),空間複雜度爲O(1)
代碼如下:
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int insertPos = 0;
for (int num: nums) {
if (num != 0) nums[insertPos++] = num;
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}