1. 程式人生 > >[leetcode][easy][Array][905][Sort Array By Parity]

[leetcode][easy][Array][905][Sort Array By Parity]

Sort Array By Parity

題目連結

題目描述

給定一個非負整型陣列A,返回一個數組,陣列中靠前的位置是A中的偶數,靠後的位置是A中的奇數。偶數範圍內順序不限,奇數也是。

約定

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

示例

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.

解答

class Solution
{
public:
    vector<int> sortArrayByParity(vector<int>& A)
    {
        vector<int> result;
        for (int i = 0; i < A.size(); i++)
        {
            if (A[i] % 2)
            {
                result.insert(result.begin(), A[i]);
            }
            else
            {
                result.push_back(A[i]);
            }
        }
        return result;
    }
};