Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

练习题8:找出终点城市 #19

Open
chenhuiYj opened this issue Jul 6, 2020 · 0 comments
Open

练习题8:找出终点城市 #19

chenhuiYj opened this issue Jul 6, 2020 · 0 comments

Comments

@chenhuiYj
Copy link
Owner

chenhuiYj commented Jul 6, 2020

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

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

实例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"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/destination-city
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路
1.首先,终点城市在 paths 里面只会出现一次
2.根据 1 的过滤(paths扁平化后过滤),最后会得到两个城市,始点城市和终点城市。
3.根据 2 的过滤,得到的两个城市,最后如果在 paths 里面的 index 是偶数的就是始点城市,如果是奇数终点城市。

代码如下

var destCity = function(paths) {
    let _paths=paths.flat(2)
    let _pathKey=[...new Set(_paths)]
    return _pathKey.filter((item,index)=>JSON.stringify(paths).split(item).length===2&&index%2===1)[0]
};

// 一行代码实现

var destCity = function(paths) {
    return [...new Set(paths)].flat(2).filter((item,index)=>JSON.stringify(paths).split(item).length===2&&index%2===1)[0]
};

方式二

var destCity = function(paths) {
    let _paths=paths.flat(2)
    let resultCount={}
    let resultIndex={}
    for(let i=0;i<_paths.length;i++){
       resultCount[_paths[i]]=resultCount[_paths[i]]?++resultCount[_paths[i]]:1
       resultIndex[_paths[i]]=resultIndex[_paths[i]]?resultIndex[_paths[i]]+''+i:i
    }
    for(let item of _paths){
       if(resultCount[item]===1&&resultIndex[item]%2){
            return item
        }
    }
};

方式三

var destCity = function(paths) {
    let _pathFirst=[]
    let _pathEnd=[]
    paths.forEach(item=>{
        _pathFirst.push(item[0])
        _pathEnd.push(item[1])
    })
    for(let item of _pathEnd){
        if(!_pathFirst.includes(item)){
            return item
        }
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant