【算法】1436. 旅行终点站(多语言实现)

166 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情


1436. 旅行终点站:

给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAicityA_i, cityBicityB_i] 表示该线路将会从 cityAicityA_i 直接前往 cityBicityB_i 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。

题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行终点站。

样例 1:

输入:
	paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
	
输出:
	"Sao Paulo" 
	
解释:
	从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> "Lima" -> "Sao Paulo"

样例 2:

输入:
	paths = [["B","C"],["D","B"],["C","A"]]
	
输出:
	"A"
	
解释:
	所有可能的线路是:
	"D" -> "B" -> "C" -> "A". 
	"B" -> "C" -> "A". 
	"C" -> "A". 
	"A". 
	显然,旅行终点站是 "A"

样例 3:

输入:
	paths = [["A","Z"]]
	
输出:
	"Z"

提示:

  • 1 <= paths.length <= 100
  • paths[i].length == 2
  • 1 <= cityAicityA_i.length, cityBicityB_i.length <= 10
  • cityAicityA_i != cityBicityB_i
  • 所有字符串均由大小写英文字母和空格字符组成。

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 需要找到仅出现在到达,未出现在出发的城市。
  • 可以先将出发的城市放到hash集中,然后再次遍历到达城市找到未出现在出发的hash集中的城市即是结果。

题解

java

class Solution {
    public String destCity(List<List<String>> paths) {
        Set<String> from = new HashSet<>();

        for (List<String> path : paths) {
            from.add(path.get(0));
        }
        for (List<String> path : paths) {
            if (!from.contains(path.get(1))) {
                return path.get(1);
            }
        }

        return null;
    }
}

c

char * destCity(char *** paths, int pathsSize, int* pathsColSize){
    char *to = paths[0][1];
    for (int i = 1; i < pathsSize; i++) {
        if (strcmp(to, paths[i][0]) == 0) {
            to = paths[i][1];
            i = 0;
        }
    }
    return to;
}

c++

class Solution {
public:
    string destCity(vector<vector<string>>& paths) {
        unordered_set<string> from;
        for (vector<string>& path : paths) {
            from.insert(path[0]);
        }
        for (vector<string>& path : paths) {
            if (!from.count(path[1])) {
                return path[1];
            }
        }
        return nullptr;
    }
};

python

class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
        from_cities = {path[0] for path in paths}
        return next(path[1] for path in paths if path[1] not in from_cities)
        

go

func destCity(paths [][]string) string {
    from := map[string]struct{}{}
    for _, path := range paths {
        from[path[0]] = struct{}{}
    }
    for _, path := range paths {
        if _, has := from[path[1]]; !has {
            return path[1]
        }
    }
    return ""
}

rust

impl Solution {
    pub fn dest_city(paths: Vec<Vec<String>>) -> String {
        let mut from = paths.iter().map(|path|{
            path[0].clone()
        }).collect::<std::collections::HashSet<_>>();
        paths.iter().find(|path|{
            !from.contains(&path[1])
        }).unwrap()[1].clone()
    }
}

typescript

function destCity(paths: string[][]): string {
    const from = paths.map(path => path[0]);
    return paths.find(path => from.indexOf(path[1]) == -1)[1];
};

原题传送门:https://leetcode-cn.com/problems/destination-city/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~