905. Sort Array By Parity

Link: https://leetcode.com/problems/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 <= A.length <= 5000
  • 0 <= A[i] <= 5000

題目翻譯:

給定一個非負整數數組 A,返回一個由 A 的所有偶數元素組成的數組,後跟 A 的所有奇數元素。

您可以返回滿足此條件的任何答案數組。

程式思路:

用雙指標一個跑前面一個跑後面。前指標偵測到奇數,後指標偵測偶數,兩兩交換數值,直到前指標越過後指標,停止偵測交換。

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& A) {
        int fpos = 0,lpos = A.size()-1;
        while(fpos < lpos){
            //cout << A[fpos] << "," << A[lpos] << endl;
            if(A[fpos]%2 == 1 && A[lpos]%2 == 0) {
                swap(A[fpos++],A[lpos--]);
            }
            if(A[fpos] %2 == 0) //even
                fpos ++;
            if(A[lpos] %2 == 1) // odd
                lpos --;
        }
        return A;
    }
};

  目錄