-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalternatePositiveNegative.java
More file actions
40 lines (34 loc) · 1.2 KB
/
alternatePositiveNegative.java
File metadata and controls
40 lines (34 loc) · 1.2 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
import java.util.ArrayList;
class Solution {
void rearrange(ArrayList<Integer> arr) {
// Step 1: Separate positive and negative elements
ArrayList<Integer> positive = new ArrayList<>();
ArrayList<Integer> negative = new ArrayList<>();
for (int num : arr) {
if (num >= 0) {
positive.add(num);
} else {
negative.add(num);
}
}
// Step 2: Merge positive and negative arrays alternately
int posIndex = 0, negIndex = 0, i = 0;
// While there are both positive and negative elements
while (posIndex < positive.size() && negIndex < negative.size()) {
if (i % 2 == 0) {
arr.set(i, positive.get(posIndex++));
} else {
arr.set(i, negative.get(negIndex++));
}
i++;
}
// If there are remaining positive elements
while (posIndex < positive.size()) {
arr.set(i++, positive.get(posIndex++));
}
// If there are remaining negative elements
while (negIndex < negative.size()) {
arr.set(i++, negative.get(negIndex++));
}
}
}