LeetCode OJ-283. Move Zeroes

来源:互联网 发布:mmd各种动作数据百度云 编辑:程序博客网 时间:2024/05/18 00:02
283. Move Zeroes

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.

使用插入排序的思路就好了,取一个非0的元素,只要前面的元素为0,就往前移动。代码如下:
void moveZeroes(int* nums, int numsSize) {    int i, j;    int tmp;    for (i = 1; i < numsSize; ++i) {        if (nums[i] == 0) {            continue ;        }                tmp = nums[i];        for (j = i - 1; j >= 0 && (nums[j] == 0); --j) {            nums[j + 1] = nums[j];        }                nums[j + 1] = tmp;    }}


0 0