leetcode 283. Move Zeroes(C语言)

来源:互联网 发布:机器人焊接软件 编辑:程序博客网 时间:2024/05/18 03:54

呃……还是第四天……

其实我前几天都是在发上一天写的题,为了保证每天写的感想思路啥的都是最新鲜的,索性今天把存货也发出来了……


贴原题:

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:

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解析:

这道题的目的很明确,就是要把所有的0都挪到非0元素的后面去,也就是要把非0元素从第一个挨个往后排,排完之后剩下的几位挨个补0就行了。

不过这道题是我头一次提交之后显示fail的,因为没有考虑到第一个元素不是0以及一个数组里没有0的情况。

我的解题思路呢,就是设一个变量,记录非零元素排到的位置,初始值为0。当遇到非零元素时就把这个元素移到那个位置,然后把记录位置+1。

如果,该非零元素就在记录位置,那么不需要任何动作;否则,则需要在移完之后把该点置为0。

贴我的C代码:

void moveZeroes(int* nums, int numsSize) {    for(int i=0, j=0; i<numsSize; i++)    {        if(*(nums+i))        {            *(nums+j)=*(nums+i);            if(i!=j)            {                *(nums+i)=0;            }            j++;        }    }}