温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

LeetCode283. Move ZeroesC语言

发布时间:2020-06-16 11:40:55 来源:网络 阅读:379 作者:努力的C 栏目:编程语言
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.容易理解简单粗暴。

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI