遍歷一遍,用兩個指針分別記錄奇數和偶數,當前是奇數則存入奇數位,偶數則存入偶數位,一種是另開一個數組,一種是在原有的數組改,當遇到不匹配的時候,查找到另一個不匹配的進行交換。
function sortArrayByParityII(A: number[]): number[] {
let i = 0;
let j = 1;
let result = Array.of(A.length)
for(let index =0; index< A.length; index++) {
if(A[index]%2===0){
result[i]=A[index]
i+=2
} else {
result[j]=A[index]
j+=2
}
}
return result
};
function sortArrayByParityII2(A: number[]): number[] {
let j = 1;
for(let i =0; i< A.length; i+=2) {
if(A[i]%2===1){
while(A[j]%2===1) {
j+=2
}
let temp = A[j]
A[j] = A[i]
A[i] = temp
}
return A
};