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

思路

我们可以借鉴一下快排的思想,设两个指针i,j分别指向数组头,数组尾,然后检查i指向的如果是偶数,i++,j如果指向的是奇数,j--,如果遇到了i指向奇数,j指向偶数,则两个交换一下。看了一下讨论区的代码,大体都是这么做的。

代码

class Solution {
public:
    vector sortArrayByParity(vector& A) {
        int i = 0;
        int j = A.size()-1;
        int tmp;
        while(i

你可能感兴趣的:(905. Sort Array By Parity)