[Leetcode学习-java]Clone Graph(地图深克隆)

问题:

难度:medium

说明:

对一个相互依赖的对象,进行一次深克隆,返回一个全新的对象。

问题链接:https://leetcode.com/problems/clone-graph/

输入案例:

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

我的代码:

其实这个和spring的解决依赖循环一个意思,也跟 tow sum 一样的解决方法,使用一个 map 进行缓存,然后进行递归实例化未实例化的对象,再进行 neighbors 添加。

public class Solution {
    public Node cloneGraph(Node node) {
        if (node == null) {
            return node;
        }
        // 搞个缓存
        HashMap<Integer, Node> cacheMap = new HashMap<Integer, Node>();
        return clone(node, cacheMap);
    }
    
    public Node clone(Node node, HashMap<Integer, Node> cacheMap) {
        Node newNode = new Node();
        newNode.val = node.val;
        newNode.neighbors = new ArrayList<>();
        cacheMap.put(node.val, newNode);
        for(Node ne : node.neighbors) {
            if(cacheMap.containsKey(ne.val)) {
                newNode.neighbors.add(cacheMap.get(ne.val));
            }
            else {
                Node one = clone(ne, cacheMap); // 递归逐个实例化
                one.val = ne.val;
                newNode.neighbors.add(one);
            }
        }
        return newNode;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值