forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rearrange-array-elements-by-sign.cpp
82 lines (79 loc) · 1.99 KB
/
rearrange-array-elements-by-sign.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
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
// Time: O(n)
// Space: O(1)
// two pointers
class Solution {
public:
vector<int> rearrangeArray(vector<int>& nums) {
int pos = 0, neg = 1;
vector<int> result(size(nums));
for (const auto& x : nums) {
if (x > 0) {
result[pos] = x;
pos += 2;
} else {
result[neg] = x;
neg += 2;
}
}
return result;
}
};
// Time: O(n)
// Space: O(1)
// generator
class Solution2 {
public:
vector<int> rearrangeArray(vector<int>& nums) {
int pos = 0, neg = 0;
auto next_pos = [&nums, &pos]() {
for (; pos < size(nums); ++pos) {
if (nums[pos] > 0) {
return nums[pos++];
}
}
return -1;
};
auto next_neg = [&nums, &neg]() {
for (; neg < size(nums); ++neg) {
if (nums[neg] < 0) {
return nums[neg++];
}
}
return -1;
};
vector<int> result;
for (int i = 0; i < size(nums); ++i) {
if (i % 2 == 0) {
result.emplace_back(next_pos());
} else {
result.emplace_back(next_neg());
}
}
return result;
}
};
// Time: O(n)
// Space: O(1)
// array, implementation
class Solution3 {
public:
vector<int> rearrangeArray(vector<int>& nums) {
vector<int> pos, neg;
for (int i = size(nums) - 1; i >= 0; --i) {
if (nums[i] > 0) {
pos.emplace_back(nums[i]);
} else {
neg.emplace_back(nums[i]);
}
}
vector<int> result;
for (int i = 0; i < size(nums); ++i) {
if (i % 2 == 0) {
result.emplace_back(pos.back()); pos.pop_back();
} else {
result.emplace_back(neg.back()); neg.pop_back();
}
}
return result;
}
};