-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
Copy pathAccountMerge.java
85 lines (81 loc) · 2.58 KB
/
AccountMerge.java
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
package problems.medium;
import java.util.*;
/**
* Why Did you create this class? what does it do?
*/
public class AccountMerge {
public static void main(String[] args) {
List<List<String>> lists = new ArrayList<>();
lists.add(new ArrayList<String>() {{
add("David");
add("David0@m.co");
add("David1@m.co");
}});
lists.add(new ArrayList<String>() {{
add("David");
add("David3@m.co");
add("David4@m.co");
}});
lists.add(new ArrayList<String>() {{
add("David");
add("David4@m.co");
add("David5@m.co");
}});
lists.add(new ArrayList<String>() {{
add("David");
add("David2@m.co");
add("David3@m.co");
}});
lists.add(new ArrayList<String>() {{
add("David");
add("David1@m.co");
add("David2@m.co");
}});
System.out.println(new AccountMerge().accountsMerge(lists));
}
public List<List<String>> accountsMerge(List<List<String>> accounts) {
if (accounts == null || accounts.size() <= 1)
return accounts;
List<List<String>> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
for (int j = 0; j < accounts.size(); j++) {
List<String> e = accounts.get(j);
boolean yes = false;
int count = 0;
for (int i = 1; i < e.size(); i++) {
if (map.containsKey(e.get(i))) {
yes = true;
count = map.get(e.get(i));
break;
}
}
for (int i = 1; i < e.size(); i++) {
if (yes) {
map.put(e.get(i), count);
} else {
map.put(e.get(i), j);
}
}
}
Map<Integer, Set<String>> m = new HashMap<>();
for (String key : map.keySet()) {
if (!m.containsKey(map.get(key))) {
m.put(map.get(key), new HashSet<>());
}
m.get(map.get(key)).add(key);
}
for (Integer key : m.keySet()) {
List<String> ll = new ArrayList<>(m.get(key));
ll.add(accounts.get(key).get(0));
ll.sort((a, b) -> {
if (!a.contains("@"))
return -1;
if (!b.contains("@"))
return 1;
return a.compareTo(b);
});
list.add(ll);
}
return list;
}
}