LeetCode -- Move Zeroes

Question:

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.

Analysis:

问题描述:给出一个数组,写一个函数是数组中所有的0移到最后,并且保持其他的数字的顺序不变。

注意,不能额外申请一个数组。最小化额外操作数的数目。

思路:做一次for循环,每当遇到一个0时,与和他距离最近的一个不为0的数交换,T(n) = O(n).

Answer:

public class Solution {
    public void moveZeroes(int[] nums) {
        for(int i=0; i<nums.length - 1; i++) {
                if(nums[i] == 0) {
                    int j = i + 1;
                    while(nums[j] == 0 && j<nums.length - 1)
                        j++;
                    nums[i] = nums[j];
                    nums[j] = 0;
                    if(j == nums.length - 1) //如果一直遍历到了最后,则说明后面的全部是0,可以结束循环了
                        i = nums.length - 1;
                }
        }
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4821977.html