码迷,mamicode.com
首页 > 其他好文 > 详细

721. Accounts Merge

时间:2018-10-27 00:05:33      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:name   ted   ret   arc   solution   nts   ring   accounts   ash   

https://leetcode.com/problems/accounts-merge/discuss/109158/Java-Solution-(Build-graph-+-DFS-search)

 

 1 class Solution {
 2     public List<List<String>> accountsMerge(List<List<String>> accounts) {
 3         List<List<String>> res = new ArrayList<>();
 4         if(accounts == null) return res;
 5         HashMap<String, String> map = new HashMap<>();
 6         HashMap<String, Set<String>> graph = new HashMap<>();
 7         for(int j = 0; j < accounts.size(); j++){
 8             List<String> account = accounts.get(j);
 9             String name = account.get(0);
10             for(int i = 1; i < account.size(); i++){
11                 if(!graph.containsKey(account.get(i))){
12                     graph.put(account.get(i), new HashSet<>());
13                 }
14                 map.put(account.get(i), name);
15                 
16                 if(i != 1){
17                     graph.get(account.get(i)).add(account.get(i-1));
18                     graph.get(account.get(i-1)).add(account.get(i));
19                 }
20             }
21         }
22         
23         Set<String> visited = new HashSet<>();
24         for(String email : map.keySet()){
25             List<String> list = new ArrayList<>();
26             String name = map.get(email);
27             if(!visited.contains(email)){  //判断是否visited之后, 没有的话要加进去
28                 visited.add(email);
29                 dfs(graph, visited, list, email);
30                 Collections.sort(list);
31                 list.add(0, name);
32                 res.add(list);
33             }   
34         }
35         return res;    
36     }
37     
38     public void dfs(HashMap<String, Set<String>> graph, Set<String> visited, List<String> list, String email){
39         list.add(email);
40         for(String neighbor : graph.get(email)){
41             if(!visited.contains(neighbor)){
42                 visited.add(neighbor);
43                 dfs(graph, visited, list, neighbor);
44             }
45         }
46     }
47 }

 

721. Accounts Merge

标签:name   ted   ret   arc   solution   nts   ring   accounts   ash   

原文地址:https://www.cnblogs.com/goPanama/p/9859035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!