Skip to content

Commit

Permalink
New Problem Solution - "Sort Array By Parity"
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Mar 26, 2019
1 parent 2ed6107 commit 30fbc75
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ LeetCode
|941|[Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/) | [Python](./algorithms/python/ValidMountainArray/validMountainArray.py)|Easy|
|931|[Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/) | [C++](./algorithms/cpp/minimumFallingPathSum/MinimumFallingPathSum.cpp)|Medium|
|914|[X of a Kind in a Deck of Cards](https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/) | [Python](./algorithms/python/XOfAKindInADeckOfCards/hasGroupsSizeX.py)|Easy|
|905|[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C++](./algorithms/cpp/sortArrayByParity/SortArrayByParity.cpp)|Easy|
|859|[Buddy Strings](https://leetcode.com/problems/buddy-strings/description/) | [C++](./algorithms/cpp/buddyStrings/BuddyStrings.cpp)|Easy|
|858|[Mirror Reflection](https://leetcode.com/problems/mirror-reflection/description/) | [C++](./algorithms/cpp/mirrorReflection/MirrorReflection.cpp)|Medium|
|852|[Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) | [C++](./algorithms/cpp/peakIndexInAMountainArray/PeakIndexInAMountainArray.cpp)|Easy|
Expand Down
41 changes: 41 additions & 0 deletions algorithms/cpp/sortArrayByParity/SortArrayByParity.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Source : https://leetcode.com/problems/sort-array-by-parity/
// Author : Hao Chen
// Date : 2019-03-26

/*****************************************************************************************************
*
* 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:
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 them
int 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;
}
};

0 comments on commit 30fbc75

Please sign in to comment.