[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;
    }
};

猜你喜欢

转载自www.cnblogs.com/libinyl/p/10128940.html