2021.10.01 - 106.旅行终点站

1. 题目

在这里插入图片描述

2. 思路

(1) HashMap

  • 首先将所有路径加入HashMap中,然后找到不存在key的那个value即可。

(2) HashMap优化

  • 与(1)的思想基本相同,加入路径时直接排除存在key的value,相当于合并路径。

3. 代码

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public String destCity(List<List<String>> paths) {
    
    
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < paths.size(); i++) {
    
    
            map.put(paths.get(i).get(0), paths.get(i).get(1));
        }
        String res = map.get(paths.get(0).get(0));
        while (map.containsKey(res)) {
    
    
            res = map.get(res);
        }
        return res;
    }
}

class Solution1 {
    
    
    public String destCity(List<List<String>> paths) {
    
    
        Map<String, String> map = new HashMap<>();
        String start = "";
        String end = "";
        for (int i = 0; i < paths.size(); i++) {
    
    
            start = paths.get(i).get(0);
            end = paths.get(i).get(1);
            while (map.containsKey(end)) {
    
    
                String temp = map.get(end);
                map.remove(end);
                end = temp;
            }
            map.put(start, end);
        }
        String res = end;
        while (map.containsKey(res)) {
    
    
            res = map.get(res);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120581679