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:
2 <= A.length <= 20000
A.length % 2 == 0
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
類似題目:
參考資料:
https://leetcode.com/problems/sort-array-by-parity-ii/
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)