forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterleaving-positive-and-negative-numbers(AC).cpp
More file actions
54 lines (52 loc) · 1.18 KB
/
interleaving-positive-and-negative-numbers(AC).cpp
File metadata and controls
54 lines (52 loc) · 1.18 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
// O(n) time and O(1) space
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @param A: An integer array.
* @return: void
*/
void rerange(vector<int> &A) {
int n = A.size();
int n1, n2;
int i, j;
n1 = n2 = 0;
for (i = 0; i < n; ++i) {
if (A[i] < 0) {
++n1;
} else {
++n2;
}
}
if (n1 >= n2) {
i = 0;
j = 1;
while (i < n && j < n) {
if (A[i] < 0) {
i += 2;
} else if (A[j] > 0) {
j += 2;
} else {
swap(A[i], A[j]);
i += 2;
j += 2;
}
}
} else {
i = 0;
j = 1;
while (i < n && j < n) {
if (A[i] > 0) {
i += 2;
} else if (A[j] < 0) {
j += 2;
} else {
swap(A[i], A[j]);
i += 2;
j += 2;
}
}
}
}
};