移动零

题目地址: https://leetcode-cn.com/problems/move-zeroes/
题目说明: 
   给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序.
题目事例:
   输入: [0,1,0,3,12]
   输出: [1,3,12,0,0] 
题目要求:
   必须在原数组上操作,不能拷贝额外的数组
   尽量减少操作次数

方法1:先向左移动非0元素,然后将右侧非零数据进行填充0. 时间复杂度是O(n),空间复杂度是O(1).

public void moveZeroesMehtodOne (int[] nums) {
    // 1.对参数有效性进行校验
    if (nums == null || nums.length == 0) { return; }
    // 2.移动0到数组的前面部分
    int moveIndex = 0;
    for (int i=0; i<nums.length; i++) {
        if (nums[i] != 0) {
           nums[moveIndex++] = nums[i];
        }
    }         
    // 3.将数组后面的位置填充为0
    while (moveIndex < nums.length) {
        nums[moveIndex++] = 0;
    }
}

方法2:将0和非零元素进行对调. 时间复杂度是O(n),空间复杂度是O(1).

public void moveZeroesMethodTwo(int[] nums) {
   // 1.对参数有效性进行校验   
   if (nums == null || nums.length == 0) { return; }
   // 2.设置数据交换内容
   int moveIndex = 0;
   for (int i=0; i<nums.length; i++) {
       if (nums[i] != 0) {
          int tmp = nums[moveIndex];
          nums[moveIndex++] = nums[i];
          nums[i] = tmp;
       }
   }
}
原文地址:https://www.cnblogs.com/zhtzyh2012/p/14783523.html