283. Move Zeroes

来源:互联网 发布:java初级工程师考试 编辑:程序博客网 时间:2024/06/16 07:21

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.
思路:设置一个变量p,初始值为0,遍历 nums,每遇到一个非0数,则将nums[p] 设置为该非0数,随后p++。 C代码:
void moveZeroes(int* nums, int numsSize) {    int p = 0;    for(int i = 0; i < numsSize; i++) {        if(nums[i] != 0) {            nums[p++] = nums[i];        }    }    for(int i = p; i < numsSize; i++) {        nums[i] = 0;    }}
0 0
原创粉丝点击