# 905. Sort Array By Parity

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/sort-array-by-parity/description/

> 内容描述

```
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

 

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
 

Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******

贼暴力思路

```python
class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        return [i for i in A if i & 1 == 0] + [i for i in A if i & 1 == 1]
```




> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******


优化空间，in-place AC！

```python
class Solution(object):
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        idx = 0 # idx 指向的永远是奇数的 candidate
        for i in range(len(A)):
            if A[i] & 1 == 0:
                A[i], A[idx] = A[idx], A[i]
                idx += 1
        return A
```
