题目描述
- Given an array
nums
, write a function to move all0
'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.
题目解读
- 输入一个数字数组,将这个数组中的0放到最后面,然后不为0的数字按照与按顺序输出
解题思路
- 依次循环,碰到为0的数字就去和后面的不为0数字置换
Code
# include<stdio.h>
void moveZeroes(int* nums, int numsSize)
{
int i, j;
int temp;
for(i = 0; i < numsSize - 1; i ++)
{
if(nums[i] == 0)
{
for(j = i + 1; j < numsSize; j ++)
{
if(nums[j] != 0)
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
break;
}
}
}
}
for(i = 0; i < numsSize; i ++)
{
printf("%d ", nums[i]);
}
}
int main()
{
int a[10] = {0, 1, 0, 3, 12};
int numsSize = 5;
moveZeroes(a, numsSize);
}
思考
- 结果差强人意...