[LeetCode] 905. Sort Array By Parity

Description

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. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

Analyse

把数组中的所有偶数放到奇数前面去

参考快排,两个index, even指向最右的偶数,odd指向最左的奇数,两个index向中间运动,初始even为0,odd指向最右

从左到右遍历数组
当前元素是偶数,++even
当前元素是奇数,与odd指向的元素swap,--odd

Code

vector<int> sortArrayByParity(vector<int>& A)
{
    int even = 0;
    int odd = A.size()-1;

    while (even < odd)
    {
        if (A[even] % 2 != 0)
        {
            swap(A[even], A[odd]);
            --odd;
        }
        else
        {
            ++even;
        }
    }

    return A;
}

Result

Runtime: 20 ms, faster than 99.94%

posted @ 2018-10-16 10:04  arcsinW  阅读(254)  评论(0编辑  收藏  举报