905. Sort Array By Parity

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

 

C++: 32ms, 11.3MB

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& A) {
        int fistOddPos = -1;
        bool restOdd = false;
        for (size_t i = 0; i < A.size(); i++)
        {
            if (A[i] % 2 != 0)
            {
                if (fistOddPos == -1)
                {
                    fistOddPos = i;
                    restOdd = true;
                }
                continue;
            }

            if (fistOddPos != -1)
            {
                swap(A[i], A[fistOddPos]);

                if (restOdd > 0)
                {
                    fistOddPos++;
                }
            }
        }

        return A;
    }

    void swap(int& a, int& b)
    {
        int temp = b;
        b = a;
        a = temp;
    }
};

 

Python: Runtime 72ms, 13.9 MB

class Solution:
    def sortArrayByParity(self, A: List[int]) -> List[int]:
        even = []
        odd = []
        for x in A:
            if x % 2 == 0:
                even.append(x)
            else:
                odd.append(x)
        return even + odd

  

JavaScript:

posted @ 2019-03-06 09:22  czhao4  阅读(104)  评论(0)    收藏  举报