forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interleaving-positive-and-negative-numbers.cpp
57 lines (48 loc) · 1.26 KB
/
interleaving-positive-and-negative-numbers.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param A: An integer array.
* @return: void
*/
void rerange(vector<int> &A) {
int n = A.size();
// by default, start with negative in output array
int expectPostive = false;
int postiveCount = 0;
for (const auto& k : A) {
postiveCount += k > 0? 1 : 0;
}
// if there are more postive than negative, start with postive
if (2 * postiveCount > n) {
expectPostive = true;
}
int pos = 0, neg = 0;
int i = 0;
while (pos < n && neg < n) {
// A[pos] is the next negative
while (pos < n && A[pos] > 0) {
++pos;
}
// A[pos] is the next postive
while (neg < n && A[neg] < 0) {
++neg;
}
if (expectPostive && A[i] < 0) {
swap(A[i], A[neg]);
}
if (!expectPostive && A[i] > 0) {
swap(A[i], A[pos]);
}
if (i == pos) {
++pos;
}
if (i == neg) {
++neg;
}
expectPostive = !expectPostive;
++i;
}
}
};