前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >​LeetCode刷题实战332:重新安排行程

​LeetCode刷题实战332:重新安排行程

作者头像
程序员小猿
发布2021-07-29 14:39:18
2350
发布2021-07-29 14:39:18
举报
文章被收录于专栏:程序IT圈程序IT圈

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 重新安排行程,我们先来看题面:

https://leetcode-cn.com/problems/reconstruct-itinerary/

You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。

所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。

例如,行程 ["JFK", "LGA"] 与 ["JFK", "LGB"] 相比就更小,排序更靠前。

假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。

示例

解题

思路:

用map记录每一个出发的城市和它能到达的城市,并用pq来给到达的城市从小到大排序

DFS,每次获取当前城市能到达的城市

如果它能到达的城市为空,则把它加入结果

否则遍历它能到达的城市,并对每一个城市DFS

把当前城市加入结果

倒序的结果即为所求

代码语言:javascript
复制
class Solution {
    public List<String> findItinerary(List<List<String>> tickets) {
        HashMap<String, PriorityQueue<String>> map = new HashMap();
        for(List<String> ticket: tickets) {
            if(map.containsKey(ticket.get(0))) {
                map.get(ticket.get(0)).add(ticket.get(1));
            } else {
                PriorityQueue<String> temp = new PriorityQueue<String>();
                temp.add(ticket.get(1));
                map.put(ticket.get(0), temp);
            }
        }
        List<String> result = new ArrayList();
        build("JFK", map, result);
        Collections.reverse(result);
        return result; 
    }
    
    void build(String from, HashMap<String, PriorityQueue<String>> map, List<String> res) {
        PriorityQueue<String> cur = map.get(from);
        while(cur!= null && !cur.isEmpty()) {
            String nfrom = cur.poll();
            build(nfrom, map, res);
        }
        res.add(from);
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-07-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例
  • 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档