Sort Array By Parity

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.ios

You may return any answer array that satisfies this condition.測試

Example 1:

Input: [3,1,2,4]this

Output: [2,4,3,1]spa

The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.指針

說明

這個題目的意思是,將一個數列中的順序調整爲:前半部分爲偶數,後半部分爲奇數。除此以外,數列沒必要有序。code

我用了快速排序的思路,從頭和尾兩邊對數列進行遍歷。排序

從左邊開始,遇到奇數就中止遍歷;而後從右邊開始進行遍歷,遇到偶數就中止遍歷。 最後將這兩個數交換順序。element

兩邊的遍歷指針相遇的時候,整個工做結束。it

MySolution

class Solution2
{
public:
    vector<int> sortArrayByBarity(vector<int> &A)
    {
        int head = 0;
        int rear = A.size()-1;
        while(head < rear)
        {
            while((A[head]%2==0) && (head < rear)) head++;
            while((A[rear]%2==1) && (head < rear)) rear--;
            if(head < rear)
                swap(A[head++],A[rear--]);
        }
        return A;
    }
};

測試代碼

#include<iostream>
#include<vector>
#include<map>


using namespace std;

class Solution2
{
public:
    vector<int> sortArrayByBarity(vector<int> &A)
    {
        int head = 0;
        int rear = A.size()-1;
        while(head < rear)
        {
            while((A[head]%2==0) && (head < rear)) head++;
            while((A[rear]%2==1) && (head < rear)) rear--;
            if(head < rear)
                swap(A[head++],A[rear--]);
        }
        return A;
    }
};

int main(void)
{
    vector<int> a;
    a.push_back(100);
    a.push_back(4);
    a.push_back(200);
    a.push_back(1);
    a.push_back(3);
    a.push_back(2);

     cout<<endl;
     cout<<"Solution2 output:";
     Solution2 s2;
     s2.sortArrayByBarity(a);
     for(int i = 0;i<a.size();i++)
         cout <<" "<<a[i];
     cout<<endl;
    return 0;
}
相關文章
相關標籤/搜索