Sort Array By Parity Solutions in C++
Number 905
Difficulty Easy
Acceptance 74.1%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/sort-array-by-parity/// Author : Hao Chen// Date : 2019-03-26class Solution {public:bool isEven(int& x) {return x % 2 == 0;}vector<int> sortArrayByParity(vector<int>& A) {//two pointer, one from left to right, another from right to left// if left is odd number and right is even number, switch themint l=0, r=A.size()-1;while ( l < r ) {if ( !isEven(A[l]) && isEven(A[r]) ) swap(A[l], A[r]);if ( isEven(A[l]) ) l++;if ( !isEven(A[r]) ) r--;}return A;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sort-array-by-parity/solution//// Author : liuyubobobo/// Time : 2018-09-15#include <iostream>#include <vector>using namespace std;/// Two Pass/// Time Complexity : O(n)/// Space Complexity: O(n)class Solution {public:vector<int> sortArrayByParity(vector<int>& A) {vector<int> ret;for(int a: A)if(a % 2 == 0)ret.push_back(a);for(int a: A)if(a % 2)ret.push_back(a);return ret;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sort-array-by-parity/solution//// Author : liuyubobobo/// Time : 2018-09-15#include <iostream>#include <vector>using namespace std;/// Sorting by custom comparator/// Time Complexity : O(nlogn)/// Space Complexity: O(1)class Solution {public:vector<int> sortArrayByParity(vector<int>& A) {sort(A.begin(), A.end(), cmp);return A;}private:static bool cmp(int a, int b){if(a % 2 != b % 2)return a % 2 == 0;elsereturn a < b;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sort-array-by-parity/solution//// Author : liuyubobobo/// Time : 2018-09-15#include <iostream>#include <vector>using namespace std;/// Rearrange in place/// Time Complexity : O(n)/// Space Complexity: O(1)class Solution {public:vector<int> sortArrayByParity(vector<int>& A) {for(int i = 0; i < A.size(); i ++)if(A[i] % 2){int j = nextEven(A, i + 1);if(j < A.size())swap(A[i], A[j]);}return A;}private:int nextEven(const vector<int>& A, int start){for(int i = start; i < A.size(); i ++)if(A[i] % 2 == 0)return i;return A.size();}};void print_vec(const vector<int>& vec){for(int e: vec)cout << e << " ";cout << endl;}int main() {vector<int> nums {3, 1, 2, 4};print_vec(Solution().sortArrayByParity(nums));return 0;}