Leetcode每日一題:992.sort-array-by-parity-ii(按奇偶排序陣列Ⅱ)

Taco_Tuesdayyy發表於2020-11-12

在這裡插入圖片描述
思路:
法1:建立一個與原陣列同大小的陣列res,兩次遍歷A,偶數放入res的偶下標,奇數放入奇下標;
法2:雙指標;
法3:雙端佇列,遍歷A,計數插入前端,偶數插入尾端,然後雙指標(1首1尾)對佇列遍歷,交換位置即可;
在這裡插入圖片描述

//兩次遍歷
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        int n = A.size();
        vector<int> ans(n);

        int i = 0;
        for (int x: A) {
            if (x % 2 == 0) {
                ans[i] = x;
                i += 2;
            }
        }
        i = 1;
        for (int x: A) {
            if (x % 2 == 1) {
                ans[i] = x;
                i += 2;
            }
        }
        return ans;
    }
};
//雙指標
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        int n = A.size();
        int j = 1;
        for (int i = 0; i < n; i += 2) {
            if (A[i] % 2 == 1) {
                while (A[j] % 2 == 1) {
                    j += 2;
                }
                swap(A[i], A[j]);
            }
        }   
        return A;
    }
};
//雙端佇列
vector<int> sortArrayByParityII(vector<int> &A)
{
    int len = A.size();
    deque<int> q;
    for (int i = 0; i < len; i++)
    {
        if ((i & 1) != (A[i] & 1))
        {
            //奇數插入到首段,偶數插入到尾端
            if (i & 1)
            {
                q.push_front(i);
            }
            else
            {
                q.push_back(i);
            }
        }
    }

    int start = 0, end = q.size() - 1;
    while (start < end)
    {
        int temp=A[q[start]];
        A[q[start]]=A[q[end]];
        A[q[end]]=temp;
        start++;
        end--;
    }
    return A;
}

相關文章