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%

  • 相关阅读:
    反向映射和写时复制
    内存分析的好blog
    minicom使用
    tee的妙用
    网络带宽
    mem analyse
    linux 应用层常用API/命令
    ubuntu 库依赖问题
    Python基础学习笔记(一:hello world)
    第7章 取消与关闭
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9796327.html
Copyright © 2011-2022 走看看