您好,欢迎访问四川鑫光豪耀机电有限公司!

咨询热线:

18980820575
✕

营山发电机维修,营山柴油发电机维修,品牌发电机维修,发电机维修服务公司

LeetCode283.MoveZeroesC语言

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.容易理解简单粗暴。

还有一个做法理解起来有点障碍。。。。。。

友情链接 :