利用HashMap,TreeMap实现结构体

本文通过一道题目展示了如何利用HashMap和TreeMap在Java中构建数据结构,解释了解题思路及代码实现。首先,用HashMap创建了输入数据的关联结构,然后用TreeMap存储从尾节点往前遍历的最大金钱数。通过队列进行遍历,更新每个节点的成本和收益。最后,从所有节点中找出最大收益。这个例子为理解并应用这两种数据结构提供了新的视角。
摘要由CSDN通过智能技术生成

通过牛客网的洗礼,小编开始发现其实数据结构描绘的一些结构图,其实也可以利用HashMap,TreeMap来实现我们脑中的虚拟图。通过一个题目一起来感受一下。
题目描述:
在这里插入图片描述
看到题目的长度,大家千万别被吓到,其实这道题目实际考察点,只有一个结构的关联建立起来,通过遍历比较大小便可以得出最终结果,而实际的难度在于我们如何构建联系,以及实现题目两个表的结构体。

解题思路:
如果这道题正面解,那么需要考虑以及遍历的次数可能多起来,时间复杂度也会增加,换个解法,既然一定要最后一个H点的参与,我们直接通过最后节点然后逐个返回遍历,尝试。

实例:
在这里插入图片描述

结构体的联系其实很简单的:

//这个是输入的二维数组,实际上就是一个多个集合的大集合,构建了图一左边的图
HashMap<Integer, ArrayList<Integer>> parents = new HashMap<>();
		for (int i = 0; i < size; i++) {
			parents.put(i, new ArrayList<Integer>());
		}
		int end = -1;
		for (int i = 0; i < dependents.length; i++) {
			boolean allZero = true;
			for (int j = 0; j < dependents[0].length; j++) {
				if (dependents[i][j] != 0) {
					parents.get(j).add(i);
					allZero = false;
				}
			}
			if (allZero) {
				end = i;
			}
		}

//这个便是从尾节点往前遍历的所有不超过time的最大金钱数
		HashMap<Integer, TreeMap<Integer, Integer>> nodeCostRMap = new HashMap<>();
		for (int i = 0; i < size; i++) {
			nodeCostRMap.put(i, new TreeMap<Integer, Integer>());
		}
		nodeCostRMap.get(end).put(times[end], revenue[end]);

遍历:

LinkedList <Integer> queue = new LinkedList<>();
        queue.add(end);
        while(!queue.isEmpty()) {
        	int cur=queue.poll();
        	for(int last:parents.get(cur)) {
        		for(Entry<Integer,Integer> entry:nodeCostRMap.get(cur).entrySet()) {
        			int lastCost=entry.getKey()+times[last];
        			int lastR=entry.getValue()+revenue[last];
        			TreeMap<Integer, Integer>lastMap=nodeCostRMap.get(last);
        			if(lastMap.floorKey(lastCost)==null||lastMap.floorKey(lastCost)<lastR) {
        				lastMap.put(lastCost, lastR);
        			}
        		}
        		queue.add(last);
        	}
        }
        TreeMap<Integer, Integer> allMap=new TreeMap<>();
        for(TreeMap<Integer, Integer> curMap:nodeCostRMap.values()) {
        	for(Entry<Integer,Integer>entry:curMap.entrySet()) {
        		int cost=entry.getKey();
        		int R=entry.getValue();
        		if(allMap.floorKey(cost)==null||allMap.get(allMap.floorKey(cost))<R) {
        			allMap.put(cost, R);
        		}
        	}
        }

好啦,希望这一个题目对你们对map有一些其他不同的想法,以及用法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值