[LeetCode] 905. Sort Array By Parity 按奇偶排序數組



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. 1 <= A.length <= 5000
  2. 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

https://leetcode.com/problems/sort-array-by-parity/discuss/170725/Know-your-C%2B%2B-Algorithms!-This-is-std%3A%3Apartition-%3A)


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


免責聲明!

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



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