# 922. Sort Array By Parity II

Given an array `A` of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever `A[i]` is odd, `i` is odd; and whenever `A[i]` is even, `i` is even.

You may return any answer array that satisfies this condition.

Example 1:

``````Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
``````

Note:

1. `2 <= A.length <= 20000`
2. `A.length % 2 == 0`
3. `0 <= A[i] <= 1000`

``````class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& A) {
vector<int> res, even, odd;
for (int num : A) {
if (num % 2 == 0) even.push_back(num);
else odd.push_back(num);
}
for (int i = 0; i < even.size(); ++i) {
res.push_back(even[i]);
res.push_back(odd[i]);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& A) {
int n = A.size(), i = 0, j = 1;
while (i < n && j < n) {
if (A[i] % 2 == 0) i += 2;
else if (A[j] % 2 == 1) j += 2;
else swap(A[i], A[j]);
}
return A;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/922

Sort Array By Parity

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

https://leetcode.com/problems/sort-array-by-parity-ii/discuss/181160/Java-two-pointer-one-pass-inplace

https://leetcode.com/problems/sort-array-by-parity-ii/discuss/193854/Linear-pass-using-2-pointers-in-C%2B%2B.

https://leetcode.com/problems/sort-array-by-parity-ii/discuss/181158/C%2B%2B-5-lines-two-pointers-%2B-2-liner-bonus

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation