This commit is contained in:
ShusenTang 2020-02-03 17:52:39 +08:00
parent ce580a3e76
commit 640fb15b08
2 changed files with 44 additions and 0 deletions

View File

@ -291,3 +291,4 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
| 661 |[Image Smoother](https://leetcode.com/problems/image-smoother)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/661.%20Image%20Smoother.md)|Easy| | | 661 |[Image Smoother](https://leetcode.com/problems/image-smoother)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/661.%20Image%20Smoother.md)|Easy| |
| 665 |[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/665.%20Non-decreasing%20Array.md)|Easy| | | 665 |[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/665.%20Non-decreasing%20Array.md)|Easy| |
| 714 |[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/714.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee.md)|Medium| | | 714 |[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/714.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee.md)|Medium| |
| 905 |[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[C++](solutions/905.%20Sort%20Array%20By%20Parity.md)|Medium| |

View File

@ -0,0 +1,43 @@
# [905. Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)
# 思路
题目要求将一个数组中的偶数放在奇数前面。很简单用两个指针i和j就可以了分别表示`a[0, 1, ..., i-1]`全部为偶数而`a[j+1, j+2, ..., n-1]`全部为奇数所以i和j初始分别为0和n-1。然后就是循环每个循环内部
* 1. 如果`A[i]`为奇数那么交换`A[i]`和`A[j]`然后将`j--`,否则`i++`
* 2. 如果`A[j]`为偶数那么交换`A[i]`和`A[j]`然后将`i++`,否则`j--`
上面的1和2单独使用也是可以的。
另外STL中`partition`所干的就是此题要求的事,它会使所有使给定比较函数返回 true 的元素放在返回false的前面所以我们只需要自定义比较函数就可以了。
# C++
``` C++
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int i = 0, j = A.size() - 1;
// 如果问题条件变一下, 例如将能被3整除的放在不能整除的前面, 我们只需要改这一行代码
# define CONDITION(i) (A[i] & 1)
while(i < j){
if(i < j && CONDITION(i)) swap(A[i], A[j--]);
else i++;
if (i < j && !CONDITION(j)) swap(A[i++], A[j]);
else j--;
}
return A;
}
};
```
## 直接使用STL中的partition
``` C++
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
partition(A.begin(), A.end(), [](int a) { return !(a & 1);});
return A;
}
};
```