LeetCode 133: Clone Graph
2016-06-07 12:41
417 查看
LeetCode 133: Clone Graph
思路
需要考虑自环和两个节点有多条边的特殊情况,这种情况下,不能生成新的节点,而是引用已有节点;利用Hashtable记录已经存放的节点;
代码
import java.util.Hashtable; public class Solution { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if (node == null) return null; UndirectedGraphNode begin = new UndirectedGraphNode(node.label); Queue<UndirectedGraphNode> oldQueue = new LinkedList<UndirectedGraphNode>(); Queue<UndirectedGraphNode> copyQueue = new LinkedList<UndirectedGraphNode>(); oldQueue.add(node); copyQueue.add(begin); Hashtable<Integer, UndirectedGraphNode> hashtable = new Hashtable<Integer, UndirectedGraphNode>(); hashtable.put(node.label, begin); while(!oldQueue.isEmpty()) { UndirectedGraphNode old = oldQueue.remove(); UndirectedGraphNode copy = copyQueue.remove(); for (UndirectedGraphNode tmp : old.neighbors) { if (hashtable.containsKey(tmp.label)) { //already existed copy.neighbors.add(hashtable.get(tmp.label)); } else { //not existed UndirectedGraphNode n = new UndirectedGraphNode(tmp.label); copy.neighbors.add(n); hashtable.put(tmp.label, n); oldQueue.add(tmp); copyQueue.add(n); } } } return begin; } }
相关文章推荐
- C#中遍历Hashtable的4种方法
- C#将HashTable中键列表或值列表复制到一维数组的方法
- asp.net基于HashTable实现购物车的方法
- 详解C#中HashTable的用法
- JAVASCRIPT HashTable
- java hashtable实现代码
- java中vector与hashtable操作实例分享
- Java中HashMap和Hashtable的区别浅析
- C#将hashtable值转换到数组中的方法
- c语言实现的hashtable分享
- 利用C语言实现HashTable
- php中hashtable实现示例分享
- 全面解析java中的hashtable
- Java中Hashtable类与HashMap类的区别详解
- 浅析java中ArrayList与Vector的区别以及HashMap与Hashtable的区别
- java中Hashtable和HashMap的区别分析
- Java中HashMap和Hashtable及HashSet的区别
- 浅析Java中Map与HashMap,Hashtable,HashSet的区别
- c#限时作业
- HashMap和HashTable的区别