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放到最后。注意不要创建新的数组和最小化所有操作的数量
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.容易理解简单粗暴。
还有一个做法理解起来有点障碍。。。。。。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。