meibin08 / free-programming-books

📚码农周报 免费的编程书籍,leetcode(力扣)题解、前端算法题,牛客网前端大厂面试题题解、提升工作效率的常用工具等📈🎉
https://susouth.com/
424 stars 60 forks source link

Array-解题:按奇偶排序数组(NO.905) #34

Open meibin08 opened 5 years ago

meibin08 commented 5 years ago

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。 你可以返回任何满足上述条件的数组作为答案。

2 <= A.length <= 20000 A.length % 2 == 0 0 <= A[i] <= 1000

原题链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii/

meibin08 commented 5 years ago

js解题:

var sortArrayByParityII = function (A) {

    let odd = [];
    let even = A.filter((k) => {
        k % 2 != 0 && odd.push(k);
        return k % 2 == 0;
    });
    if (even.length < odd.length) {
        [even, odd] = [odd, even];
    };
    A = [];
    even.map((k, v) => {
        A.push(k);
        if (v <= odd.length - 1) {
            A.push(odd[v]);
        }
    })
    //console.log(A);
    return A;
};