题目

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.

Example:

1
2
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

1
2
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

分析

此题比较基础,这就是冒泡排序的变形版,题目的要求不能新开辟新的数组空间,将所有的操作的的操作步数最小化。

C语言代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
void moveZeroes(int* nums, int numsSize) {
for(int i=0;i<numsSize;i++)
{
for (int j = i; j <numsSize ; ++j) {
if(nums[i]==0)
{
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}

}
}
}

int main()
{
int nums[]={4,2,4,0,0,3,0,5,1,0};
int numsSize=sizeof(nums)/ sizeof(int);

// 输出为[1,3,12,0,0]
// 执行函数
moveZeroes(nums,numsSize);
// 输出每个数
for(int i=0;i<numsSize;i++)
{
printf("%d,",nums[i]);
}

}