[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%

转载于:https://www.cnblogs.com/arcsinw/p/9796327.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值