【Leetcode】1436. Destination City

题目地址:

https://leetcode.com/problems/destination-city/html

给定一个数组,每一行含两个字符串分别表明两个城市,含义是第一个城市能够直达第二个城市。求那个只做为终点不做为起点的城市。题目保证答案存在且惟一。java

思路是用一个哈希表,先把做为终点的城市全加进来,而后再把做为起点的城市全删掉,题目保证答案只有一个,因此最后直接返回哈希表里仅剩的城市便可。代码以下:web

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Solution {
    public String destCity(List<List<String>> paths) {
        Set<String> set = new HashSet<>();
        for (List<String> path : paths) {
            set.add(path.get(1));
        }
    
        for (List<String> path : paths) {
            set.remove(path.get(0));
        }
        
        return set.iterator().next();
    }
}

时间复杂度 O ( n l ) O(nl) 数组