# 283. Move Zeroes

## 1.問題&#x20;

* 給予一個array nums, 寫一個function可以將所有的0到array的後面&#x20;

![](/files/-LHwUB4-LCYtH-CAWnJk)

## 2.想法&#x20;

* 第一種想法是掃描整個array, 一碰到0就swap到最後面, 但這種作法的複雜度很高
* 第二種做法是只要一碰到不為0的元素, 就直接assign到陣列前方, 並記錄index

## 3.程式碼

* 第一種做法

```
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int index = 0, cnt = 0;
        while (cnt < (nums.size())) {
            if (nums[index] == 0){
                for (int i = index; i < nums.size(); i++) {
                    if (nums[i] == 0) {
                        for (int j = i; j < nums.size() - 1; j++) { 
                            swap(nums, j, j + 1);
                        }   
                    }
                }
            } else {
                index++;
            }
            cnt ++;
        }
    }
private:
    void swap(vector<int>& nums, int num1, int num2) {
        int tmp = nums[num1];
        nums[num1] = nums[num2];
        nums[num2] = tmp;
    }
};
```

* 第二種做法

```
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int write = 0;
        for (int i=0; i<nums.size(); i++) {
            if (nums[i] != 0) {
                nums[write++] = nums[i];
            }
        }
        for (; write<nums.size(); write++) {
            nums[write] = 0;
        }
    }
};
```

## 4.Performance

* 第一種做法

![](/files/-LHwVvXscSUwvjwyud5h)

* 第二種做法

![](/files/-LHwW2k8ARKea6K9z4Mb)


---

# 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://jenhsuan.gitbook.io/algorithm/leetcode/283.-move-zeroes.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.
