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%

  • 相关阅读:
    Nginx工作原理
    Redis核心原理
    Nginx介绍
    资源平衡与资源平滑
    HDFS(Hadoop Distributed File System)的组件架构概述
    HBase的应用场景及特点
    HBase详解
    Nginx被动健康检查和主动健康检查
    lsof 详解
    Dockerfile文件详解
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9796327.html
Copyright © 2011-2022 走看看