• 算法
    • 1.首先从数组头开始填充非0元素
    • 2.剩下的全是0
public void moveZeroes(int[] nums) {
    if (nums == null || nums.length == 0) {
        return;
    }

    int i = 0;
    for (int x : nums) {
        if (x != 0) {
            nums[i++] = x;
        }
    }
    while (i < nums.length) {
        nums[i++] = 0;
    }
}
func moveZeroes(nums []int)  {
    if nums == nil || len(nums) == 0 {
        return
    }

    i := 0
    for _, x := range nums {
        if x != 0 {
            nums[i] = x
            i++
        }    
    }
    for i < len(nums) {
        nums[i] = 0
        i++
    }
}
  • 算法
    • 1.插入排序的思想
    • 2.遇到非0的元素,往前找到最左边的0与之交换即可
public void moveZeroes(int[] nums) {
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] != 0) {
            int j = i - 1;
            while (j >= 0 && nums[j] == 0) {
                j--;
            }
            swap(nums, j+1, i);
        }
    }
}

private void swap(int[] nums, int x, int y) {
    int temp = nums[x];
    nums[x] = nums[y];
    nums[y] = temp;
}
func moveZeroes(nums []int)  {
    for i := 1; i < len(nums); i++ {
        if nums[i] != 0 {
            j := i - 1
            for j >= 0 && nums[j] == 0 {
                j--
            }
            nums[i], nums[j+1] = nums[j+1], nums[i]
        }
    }
}