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
这题让我们将一个数组梳理成两部分,第一个部分都是偶数,第二个部分都是奇数。
截图的思路比较简单,我们准备首尾两个指针,分别指向元素首部和尾部,首先判断首指针,假设是偶数,跳过,奇数的话扫描尾指针,是偶数的话进行一次调换,直到两个指针相交。
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int fi = 0;
int li = A.size() - 1;
while (fi < li) {
if (A[fi] % 2 == 0) {
fi++;
continue;
}
for (li; li > fi; li--) {
if (A[li] % 2 == 0) {
swap(A[li], A[fi]);
break;
}
}
if (li <= fi) {
return A;
}
}
return A;
}
};