[LeetCode] 922. Sort Array By Parity II 按奇偶排序數組之二



Given an array `A` of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Note:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000

這道題是之前那道 [Sort Array By Parity](https://www.cnblogs.com/grandyang/p/11173513.html) 的拓展,那道讓把奇數排在偶數的后面,而這道題是讓把偶數都放在偶數坐標位置,而把奇數都放在奇數坐標位置。博主最先想到的方法非常簡單粗暴,直接分別將奇數和偶數提取出來,存到兩個不同的數組中,然后再把兩個數組,每次取一個放到結果 res 中即可,參見代碼如下:
解法一:
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        vector<int> res, even, odd;
        for (int num : A) {
            if (num % 2 == 0) even.push_back(num);
            else odd.push_back(num);
        }
        for (int i = 0; i < even.size(); ++i) {
            res.push_back(even[i]);
            res.push_back(odd[i]);
        }
        return res;
    }
};

論壇上還有一種更加簡單的方法,不需要使用額外的空間,思路是用兩個指針,i指針一直指向偶數位置,j指針一直指向奇數位置,當 A[i] 是偶數時,則跳到下一個偶數位置,直到i指向一個偶數位置上的奇數,同理,當 A[j] 是奇數時,則跳到下一個奇數位置,直到j指向一個奇數位置上的偶數,當 A[i] 和 A[j] 分別是奇數和偶數的時候,則交換兩個數字的位置,從而滿足題意,參見代碼如下:
解法二:
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        int n = A.size(), i = 0, j = 1;
        while (i < n && j < n) {
            if (A[i] % 2 == 0) i += 2;
            else if (A[j] % 2 == 1) j += 2;
            else swap(A[i], A[j]);
        }
        return A;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/922


類似題目:

Sort Array By Parity


參考資料:

https://leetcode.com/problems/sort-array-by-parity-ii/

https://leetcode.com/problems/sort-array-by-parity-ii/discuss/181160/Java-two-pointer-one-pass-inplace

https://leetcode.com/problems/sort-array-by-parity-ii/discuss/193854/Linear-pass-using-2-pointers-in-C%2B%2B.

https://leetcode.com/problems/sort-array-by-parity-ii/discuss/181158/C%2B%2B-5-lines-two-pointers-%2B-2-liner-bonus


[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM