forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
50 lines (38 loc) · 987 Bytes
/
main3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// 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;
}