【LeetCode】905. Sort Array By Parity (javascript版)

905.Sort Array By Parity

Given an array A of non-negative integers, return an array consisting
of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

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.

Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000

题目:按奇偶排序数组

给定一个非赋整数数组A,返回一个数组,在该数组中,A的所有偶数元素之后跟着所有奇数元素。

解题思路:遍历数组,判断奇偶,然后利用数组函数push()和unshift()的特性,对数组进行奇偶排序。

/**
 * @param {number[]} A
 * @return {number[]}
 */
var sortArrayByParity = function(A) {
    let arrTemp = [];
    A.forEach((item)=>{
      if(item%2 === 0){
         arrTemp.unshift(item);
      }else{
          arrTemp.push(item);
      }  
    })
    return arrTemp;
};

 

你可能感兴趣的:(【LeetCode】,leetcode,javascript)