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
.html
You may return any answer array that satisfies this condition.git
Example 1:github
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,這樣操做下來,一樣能夠將全部的偶數都放在奇數前面,參見代碼以下:this
解法二:指針
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,是專門用來給數組從新排序的,不過咱們要重寫排序方式,將偶數的都放在前面便可,參見代碼以下:code
解法三:htm
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