查看: 521| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[学Java/C#] 787这个题怎么突然超时了

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
感觉要求变高了

我的代码如下。朋友说,需要用dp来记录??? 我都不懂为啥呢?
  1. class Solution {
  2.    
  3.     public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
  4.          
  5.         Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
  6.         
  7.         for(int[] f : flights){
  8.             
  9.             if(!map.containsKey(f[0])){
  10.                  
  11.                 map.put(f[0], new HashMap<>());
  12.             }
  13.             
  14.             map.get(f[0]).put(f[1],f[2]);
  15.             
  16.         }
  17.         
  18.         Queue<int[]> queue = new PriorityQueue<>( (a,b) -> (a[0] - b[0]) );
  19.         
  20.         Set<Integer> set = new HashSet<>();
  21.         
  22.         set.add(src);
  23.         
  24.         int best[] = new int[n+1];
  25.         
  26.         Arrays.fill(best, Integer.MAX_VALUE);

  27.         best[src] = 0;

  28.         queue.add(new int[]{0, src, k+1});
  29.            
  30.         while( !queue.isEmpty() ){
  31.             
  32.             int[] curr = queue.poll();
  33.             
  34.             int currPrice = curr[0];
  35.             int currLocation = curr[1];
  36.             int stopsLeft = curr[2];
  37.             
  38.             if(currLocation == dst) return currPrice;
  39.             
  40.             Map<Integer, Integer> neighhors = map.getOrDefault(currLocation, new HashMap<>());
  41.             
  42.             if(stopsLeft > 0){
  43.                
  44.                 for(int nei : neighhors.keySet()){
  45.                     
  46.                         set.add(nei);
  47.                     
  48.                         int newPrice = currPrice + neighhors.get(nei);
  49.                     
  50.                         if( newPrice < best[nei] ) {
  51.                             queue.add(new int[]{currPrice + neighhors.get(nei), nei, stopsLeft - 1});
  52.                            
  53.                         }
  54.                 }
  55.             }
  56.     }
  57.         
  58.      return -1;
  59.     }
  60. }
复制代码

上一篇:想问一下关于O(1) Space遍历二叉树的问题
下一篇:请问1060 和 1539 的差别是什么
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表