Skip to content

Commit a4a6564

Browse files
authored
Update rearrange-array-elements-by-sign.cpp
1 parent 673ad73 commit a4a6564

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

C++/rearrange-array-elements-by-sign.cpp

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,43 @@ class Solution {
2222

2323
// Time: O(n)
2424
// Space: O(1)
25-
// array, implementation
25+
// generator
2626
class Solution2 {
27+
public:
28+
vector<int> rearrangeArray(vector<int>& nums) {
29+
int pos = 0, neg = 0;
30+
auto next_pos = [&nums, &pos]() {
31+
for (; pos < size(nums); ++pos) {
32+
if (nums[pos] > 0) {
33+
return nums[pos++];
34+
}
35+
}
36+
return -1;
37+
};
38+
auto next_neg = [&nums, &neg]() {
39+
for (; neg < size(nums); ++neg) {
40+
if (nums[neg] < 0) {
41+
return nums[neg++];
42+
}
43+
}
44+
return -1;
45+
};
46+
vector<int> result;
47+
for (int i = 0; i < size(nums); ++i) {
48+
if (i % 2 == 0) {
49+
result.emplace_back(next_pos());
50+
} else {
51+
result.emplace_back(next_neg());
52+
}
53+
}
54+
return result;
55+
}
56+
};
57+
58+
// Time: O(n)
59+
// Space: O(1)
60+
// array, implementation
61+
class Solution3 {
2762
public:
2863
vector<int> rearrangeArray(vector<int>& nums) {
2964
vector<int> pos, neg;

0 commit comments

Comments
 (0)