leetcode Move Zeroes

来源:互联网 发布:数据透视表生成图表 编辑:程序博客网 时间:2024/06/03 20:34

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.

  1. Minimize the total number of operations.

思路:两根指针,一个probe探索非0的数,一个ptr存储非0的数。
探索指针在前,遇到非零的就存在ptr所指向的位置。探索指针走到数组末尾,ptr--->末尾的这些空间全部置0即可。

void moveZeroes(int* nums, int numsSize) {    int *probe;    int *ptr;        ptr=probe=nums;        for(int i=0;i<numsSize;i++){        if(nums[i] !=0 )        {            *ptr = nums[i];            ptr++;        }    }        while(ptr < nums+numsSize){        *ptr++=0;    }        }


0 0
原创粉丝点击