-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_array_by_parity2.cpp
More file actions
82 lines (75 loc) · 1.9 KB
/
sort_array_by_parity2.cpp
File metadata and controls
82 lines (75 loc) · 1.9 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* =====================================================================================
*
* Filename: sort_array_by_parity2.cpp
*
* Description: 922. Sort Array By Parity II
* https://leetcode.com/problems/sort-array-by-parity-ii/
*
* Version: 1.0
* Created: 03/04/23 17:43:42
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::vector;
// Extra spaces
class Solution1 {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
auto is_odd = [](const int n) { return (n % 2 == 1); };
vector<int> ans(nums.size());
int i = 0;
int j = 1;
for (const int n : nums) {
if (!is_odd(n)) {
ans[i] = n;
i += 2;
} else {
ans[j] = n;
j += 2;
}
}
return ans;
}
};
// No spaces, two pointers
class Solution2 {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
auto is_odd = [](const int n) { return (n % 2 == 1); };
for (int i = 0, j = 1; i < nums.size(); i += 2) {
if (!is_odd(nums[i])) {
continue;
}
while (is_odd(nums[j])) {
j += 2;
}
std::swap(nums[i], nums[j]);
}
return nums;
}
};
TEST(Solution, sortArrayByParityII) {
auto verify = [](const vector<int>& nums) {
for (int i = 0; i < nums.size(); i++) {
EXPECT_EQ((i ^ nums[i]) % 2, 0);
}
};
vector<vector<int>> cases = {vector<int>{2, 3}, vector<int>{4, 2, 5, 7},
vector<int>{2, 3, 1, 1, 4, 0, 0, 4, 3, 3}};
for (auto& c : cases) {
auto c1 = c;
verify(Solution1().sortArrayByParityII(c));
auto c2 = c;
verify(Solution2().sortArrayByParityII(c));
}
}