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
這道題讓我們給數組重新排序,使得偶數都排在奇數前面,並不難。最直接的做法就是分別把偶數和奇數分別放到兩個數組中,然后把奇數數組放在偶數數組之后,將拼接成的新數組直接返回即可,參見代碼如下:
解法一:
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
vector<int> even, odd;
for (int num : A) {
if (num % 2 == 0) even.push_back(num);
else odd.push_back(num);
}
even.insert(even.end(), odd.begin(), odd.end());
return even;
}
};
我們也可以優化空間復雜度,不新建額外的數組,而是采用直接交換數字的位置,使用兩個指針i和j,初始化均為0。然后j往后遍歷,若遇到了偶數,則將 A[j] 和 A[i] 交換位置,同時i自增1,這樣操作下來,同樣可以將所有的偶數都放在奇數前面,參見代碼如下:
解法二:
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
for (int i = 0, j = 0; j < A.size(); ++j) {
if (A[j] % 2 == 0) swap(A[i++], A[j]);
}
return A;
}
};
我們還可以使用 STL 的內置函數 partition,是專門用來給數組重新排序的,不過我們要重寫排序方式,將偶數的都放在前面即可,參見代碼如下:
解法三:
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
partition(A.begin(), A.end(), [](auto a) { return a % 2 == 0; });
return A;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/905
參考資料:
https://leetcode.com/problems/sort-array-by-parity/
https://leetcode.com/problems/sort-array-by-parity/discuss/170734/C%2B%2BJava-In-Place-Swap
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)