LeetCode官方题解及解析：905. Sort Array By Parity

# 题目

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:

Note:

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

# 解答1[Java]：二次筛选

## 复杂度分析

• Time Complexity: $O(N)$, where $N$ is the length of A.
• Space Complexity: $O(N)$ for the sort, depending on the built-in implementation of sort.

# 解答2[Java]：使用Comparator()

## 时间复杂度

• Time Complexity: $O(NlogN)$, where $N$ is the length of A.
• Space Complexity: $O(N)$ for the sort, depending on the built-in implementation of sort.

# 解答3[Java]：使用快排

## 思路

We’ll maintain two pointers i and j. The loop invariant is everything below i has parity 0 (ie. A[k] % 2 == 0 when k < i), and everything above j has parity 1.

Then, there are 4 cases for (A[i] % 2, A[j] % 2):

• If it is (0, 1), then everything is correct: i++ and j--.
• If it is (1, 0), we swap them so they are correct, then continue.
• If it is (0, 0), only the i place is correct, so we i++ and continue.
• If it is (1, 1), only the j place is correct, so we j-- and continue.

Throughout all 4 cases, the loop invariant is maintained, and j-i is getting smaller. So eventually we will be done with the array sorted as desired.

## 时间复杂度

• Time Complexity: $O(N)$, where $N$ is the length of A. Each step of the while loop makes j-idecrease by at least one. (Note that while quicksort is $O(NlogN)$ normally, this is $O(N)$ because we only need one pass to sort the elements.)
• Space Complexity: $O(1)$ in additional space complexity.