---
# System prepended metadata

title: 905. Sort Array By Parity
tags: [pointer, Leetcode, swap, python, c++, easy]

---

###### tags: `Leetcode` `easy` `pointer` `swap` `python` `c++`

# 905. Sort Array By Parity

## [題目連結:] https://leetcode.com/problems/sort-array-by-parity/description/

## 題目:
Given an integer array ```nums```, move all the even integers at the beginning of the array followed by all the odd integers.

Return **any array** that satisfies this condition.

**Example 1:**
```
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
```
**Example 2:**
```
Input: nums = [0]
Output: [0]
```

## 解題想法:
* 題目為將數組中:
    * 偶數放數組前面
    * 奇數放數組後面

* 使用pointer判斷當前奇、偶並交換即可

## Python:
``` python=
class Solution(object):
    def sortArrayByParity(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        head=0 #判斷當前是否為偶數
        tail=len(nums)-1 #判斷當前是否為奇數
        while head<=tail:
            if (nums[head]%2)!=0: #奇數
                nums[head],nums[tail]=nums[tail],nums[head]
                tail-=1 #往前
            else:
                head+=1 #為偶數正常往後判斷
        return nums
    
if __name__=='__main__':
    result=Solution()
    ans=result.sortArrayByParity(nums = [3,1,2,4])
    print(ans) #[4, 2, 1, 3]
```

## C++:
``` cpp=
class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        int head=0, tail=nums.size()-1;
        while (head<=tail){
            if (nums[head]%2!=0){
                swap(nums[head],nums[tail]);
                tail-=1;
            }
            else
                head+=1;
        }
        return nums;
    }
};
```