zoukankan      html  css  js  c++  java
  • [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%

  • 相关阅读:
    垃圾回收机制,正则模块
    日常模块
    文件路径带有字符串的处理方法
    QT进制之间的相互转换
    4-7 selectors模块
    4-5 异步IO模型
    4-4 多路复用IO模型
    4-3 非阻塞IO
    4-2 阻塞IO
    4-1 IO模型介绍
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9796327.html
Copyright © 2011-2022 走看看