File tree 1 file changed +48
-0
lines changed
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/accounts-merge/description/
2
+
3
+
4
+ class Solution {
5
+ public:
6
+ vector<int > parent;
7
+ int find_set (int x){
8
+ if (parent[x] == x) return x;
9
+ return parent[x] = find_set (parent[x]);
10
+ }
11
+
12
+ void make_union (int x, int y){
13
+ int a = find_set (x);
14
+ int b = find_set (y);
15
+ if (a != b){
16
+ parent[a] = b;
17
+ }
18
+ }
19
+
20
+ vector<vector<string>> accountsMerge (vector<vector<string>>& accounts) {
21
+ int n = accounts.size ();
22
+ parent.resize (n);
23
+ unordered_map<string, int > emailtoId;
24
+ for (int i = 0 ; i<n; i++){
25
+ parent[i] = i;
26
+ for (int j = 1 ; j<accounts[i].size (); j++){
27
+ if (emailtoId.find (accounts[i][j]) != emailtoId.end ()){
28
+ make_union (emailtoId[accounts[i][j]], i);
29
+ }
30
+ else {
31
+ emailtoId[accounts[i][j]] = parent[i];
32
+ }
33
+ }
34
+ }
35
+ unordered_map<int , vector<string>> newaccounts;
36
+ for (auto it : emailtoId){
37
+ newaccounts[find_set (it.second )].push_back (it.first );
38
+ }
39
+ vector<vector<string>> ans;
40
+ for (auto &it : newaccounts){
41
+ auto &emails = it.second ;
42
+ sort (emails.begin (), emails.end ());
43
+ emails.insert (emails.begin (), accounts[it.first ][0 ]);
44
+ ans.push_back (emails);
45
+ }
46
+ return ans;
47
+ }
48
+ };
You can’t perform that action at this time.
0 commit comments