1
2
3
4
5
|
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放到最后。注意不要创建新的数组和最小化所有操作的数量
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
|
void moveZeroes( int * nums, int numsSize) {
//选择排序变一下。。。。。n*2
// int i,j;
// for(i=0;i<numsSize;i++)
// for(j=i+1;j<numsSize;j++){
// if(nums[i]==0){
// int temp=nums[i];
// nums[i]=nums[j];
// nums[j]=temp;
// }
// }
//网上的做法1.简单粗暴容易理解。只不过是分了两步而已。。。
int i;
int index=0;
for (i=0;i<numsSize;i++){
if (nums[i]!=0){
nums[index]=nums[i];
index++;
}
}
// printf("%d",index);
for (i=index;i<numsSize;i++){
nums[i]=0;
}
///还有做法2.不太容易理解,
} |
PS:维持俩指针。。。。。
一开始想到的事排序。。。。。。把0排到最后,虽然过了,但是复杂度n*2.操作数量也挺多的。
看了网上的做法1.容易理解简单粗暴。
还有一个做法理解起来有点障碍。。。。。。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1864809