topic:
Given a non-negative integer array A, half of the integers in A are odd numbers, and half of the integers are even numbers.
Sort the array so that when A[i] is odd, i is also odd; when A[i] is even, i is also even.
You can return any array that meets the above conditions as the answer.
Example:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4 ,5] will also be accepted.prompt:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
Ideas:
Iterate over the array
1) If the element is odd, put it into the corresponding odd position
2) Otherwise, put it in the corresponding even position
Code:
/**
* @param {number[]} A
* @return {number[]}
*/
var sortArrayByParityII = function (A) {
let res = [], even = 0, odd = 1;
for (let i = 0; i < A.length; i++) {
if (A[i] & 1) {
res[odd] = A[i];
odd += 2;
} else {
res[even] = A[i];
even += 2;
}
}
return res;
};