---
# System prepended metadata

title: \#283 Move Zeroes
tags: [leetcode, leetcode-easy]

---

# \#283 Move Zeroes
## *給定一數字陣列, 將此陣列中的"0"排在陣列末端, 其餘數字順序不變*
## Log
 - build 20210607 by syhuang

## 左右指標互換法
 - 用left(當為0時就和right交換,否則往右移)和right(要被交換的數,每次迴圈往右移)兩指標跑迴圈, right跑到底時就表示所有0都被換到陣列尾端
```javascript=
var moveZeroes = function(nums) {
    for(var left = right = 0; right<nums.length; right++){
        if(nums[left]==0){
            [nums[left],nums[right]] = [nums[right],nums[left]]
        }
        if(nums[left]!=0) left++;
    }
};
```
## 初見
 - javascript陣列方法unshift+splice實作
```javascript=
var moveZeroes = function(nums) {
    var p = nums.length-1;
    for(var i=0; i<nums.length; i++){
        if(nums[p] == 0) p--;
        else{
            nums.unshift(nums[p]);
            nums.splice(p+1,1);
        }
    }
};
```
## 備註
 - javascript swap寫法: [a,b] = [b,a]
## 參考
 - [參考解](https://leetcode.com/problems/move-zeroes/discuss/72011/Simple-O(N)-Java-Solution-Using-Insert-Index)
###### tags: `leetcode`, `leetcode-easy`