-
Notifications
You must be signed in to change notification settings - Fork 3
/
922.cpp
34 lines (33 loc) · 1.02 KB
/
922.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
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
int evenNext = 0;
int oddNext = 0;
int n = nums.size();
for (int i = 0; i < nums.size(); i ++) {
if (i & 1 && !(nums[i] & 1)) {
// find odd
oddNext = max(oddNext, i + 1);
for (int j = oddNext + 1; j < n; ++j) {
if (nums[j] & 1) {
oddNext = j;
break;
}
}
swap(nums[i], nums[oddNext]);
}
else if (!(i & 1) && (nums[i] & 1)) {
// find even
evenNext = max(evenNext, i + 1);
for (int j = evenNext + 1; j < n; ++j) {
if ((nums[j] & 1) == 0) {
evenNext = j;
break;
}
}
swap(nums[i], nums[evenNext]);
}
}
return nums;
}
};