forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-22-Sort Array By Parity.cpp
More file actions
62 lines (41 loc) · 1.04 KB
/
Day-22-Sort Array By Parity.cpp
File metadata and controls
62 lines (41 loc) · 1.04 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
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
// Without extra space
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n=A.size();
int j=0;
for(int i=0;i<n;i++){
if(A[i]%2==0){
swap(A[i], A[j]);
j++;
}
}
return A;
}
};
// Extra space
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n=A.size();
vector<int> res(n);
int start=0, last=n-1;
for(int i=0;i<n;i++){
if(A[i]%2==0){
res[start++]=A[i];
} else {
res[last--]=A[i];
}
}
return res;
}
};