922. Sort Array By Parity II
程序员文章站
2024-03-06 10:23:01
...
#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.
这道题的意思是,把A中的奇数放在奇数位,偶数放在偶数位。首先把奇数和偶数用两个数组保存,然后再按照这个要求拼接成一个数组。
/**
* @param {number[]} A
* @return {number[]}
*/
var sortArrayByParityII = function(A) {
var evenArr = [];
var oddArr = [];
for(var i=0;i<A.length;i++) {
if(A[i]%2===0) {
evenArr.push(A[i]);
}
else {
oddArr.push(A[i]);
}
}
var resArr = [];
for(var j=0;j<A.length;j++) {
if(j%2===0) {
resArr.push(evenArr[0]);
evenArr.splice(0,1);
}
else {
resArr.push(oddArr[0]);
oddArr.splice(0,1);
}
}
return resArr;
};
上一篇: 删除链表中重复的结点
下一篇: 实例讲解Java批量插入、更新数据