# 283. Move Zeroes (E)

Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.

**Note** that you must do this in-place without making a copy of the array.

&#x20;

**Example 1:**

```
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
```

**Example 2:**

```
Input: nums = [0]
Output: [0]
```

&#x20;

**Constraints:**

* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`

&#x20;

**Follow up:** Could you minimize the total number of operations done?

### Solution:

Version 1:&#x20;

比如说给你输入 `nums = [0,1,4,0,2]`，你的算法没有返回值，但是会把 `nums` 数组原地修改成 `[1,4,2,0,0]`。

结合之前说到的几个题目，你是否有已经有了答案呢？

题目让我们将所有 0 移到最后，其实就相当于移除 `nums` 中的所有 0，然后再把后面的元素都赋值为 0 即可。

所以我们可以复用上一题的 `removeElement` 函数：

```java
void moveZeroes(int[] nums) {
    // 去除 nums 中的所有 0
    // 返回去除 0 之后的数组长度
    int p = removeElement(nums, 0);
    // 将 p 之后的所有元素赋值为 0
    for (; p < nums.length; p++) {
        nums[p] = 0;
    }
}

// 见上文代码实现
int removeElement(int[] nums, int val);

JAVA Version:
class Solution {
    public void moveZeroes(int[] nums) {
        
        int slow = 0; 
        int fast = 0;
        while(fast<nums.length)
        {
            if(nums[fast] == 0)
            {
                fast++;
            }
            else
            {
                nums[slow] = nums[fast];
                slow++;
                fast++;
            }
        }
        
        for(int i = slow; i< nums.length; i++)
        {
            nums[i] = 0;
        }
        
    }
}
```

Version 2:

```
public class Solution {
    public void moveZeroes(int[] nums) {
        
        int pos=0;
		
		for(int i=0;i<nums.length;i++)
		{
			if(nums[i]!=0)
			{
				nums[pos]=nums[i];
				pos++;
			}
		}
		
		for(;pos<nums.length;pos++)
		{
			nums[pos]=0;
		}
        
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/6.array/283.-move-zeroes-e.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
