905. Sort Array By Parity
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.// Two pointers with extra space
vector<int> sortArrayByParity(vector<int>& A) { // time: O(n); space: O(n)
if (A.empty()) return {};
int n = A.size(), even_ptr = 0, odd_ptr = n - 1;
vector<int> res(n);
for (int num : A) {
if (num & 0x1) { // odd
res[odd_ptr--] = num;
} else { // even
res[even_ptr++] = num;
}
}
return res;
}Last updated