-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge.java
More file actions
92 lines (80 loc) · 3.32 KB
/
Merge.java
File metadata and controls
92 lines (80 loc) · 3.32 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
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
83
84
85
86
87
88
89
90
91
92
/* *****************************************************************************
* Name: Jaya Mukherjee
* Coursera User ID: 123456
* Last modified: March 29, 2021
**************************************************************************** */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Merge {
public static ArrayList<Integer> mergeTwo(ArrayList<ArrayList<Integer>> arrays,
int[] arrayLengths) {
// TODO: Implement the functionality here.
ArrayList<Integer> result = new ArrayList<Integer>();
for (int counter = 0; counter < arrays.size() - 1; counter++) {
int pos1 = 0, pos2 = 0, pos3 = 0;
ArrayList<Integer> innerList1;
if ((counter > 0) && !result.isEmpty()) {
innerList1 = new ArrayList<Integer>(result);
pos3 = result.size();
}
else {
innerList1 = arrays.get(counter);
pos3 = arrayLengths[counter];
}
ArrayList<Integer> innerList2 = arrays.get(counter + 1);
int[] list1 = innerList1.stream()
.mapToInt(Integer::intValue)
.toArray();
int[] list2 = innerList2.stream()
.mapToInt(Integer::intValue)
.toArray();
result.clear();
while ((pos1 < pos3) || (pos2 < arrayLengths[counter + 1])) {
if ((pos1 < pos3) && (pos2 < arrayLengths[counter + 1])) {
if (list1[pos1] < list2[pos2]) {
result.add(list1[pos1]);
pos1++;
}
else {
result.add(list2[pos2]);
pos2++;
}
}
else if (pos1 >= pos3) {
result.add(list2[pos2]);
pos2++;
}
else {
result.add(list1[pos1]);
pos1++;
}
}
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numArrays = Integer.parseInt(scanner.nextLine());
int arrayLengths[] = Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < numArrays; ++i) {
int[] array = Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.toArray();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int el : array) arrayList.add(Integer.valueOf(el));
arrays.add(arrayList);
}
scanner.close();
// TODO: Implement the merge() function.
ArrayList<Integer> merged = mergeTwo(arrays, arrayLengths);
StringBuffer sb = new StringBuffer();
for (int s : merged) {
sb.append(s);
sb.append(" ");
}
System.out.println(sb.toString());
}
}