問題
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 you 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.
想法 1
看到 0 出現時,就往後找非 0 的數字,將兩數交換,即可達成要求
想法 2
利用 index 紀錄非 0 數字的順序,最後再將未記錄到的 index 都填 0,速度比前者快。
code 1
void moveZeroes(int* nums, int numsSize) {
int i, j;
int tmp;
for (i=0; i<numsSize; i++) {
if (nums[i]==0) {
for (j=i+1; j<numsSize; j++) {
if (nums[j]!=0) {
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
break;
}
}
}
}
}