第一四三六题_旅行重点站
package 简单.字符串;
import java.util.*;
/**
* @author 无法手执玫瑰
* 2020/07/0021 20:40
*/
public class 第一四三六题_旅行重点站 {
/**
* 解法一:
* 思路是第一次先将每次走的终点存入集合中,然后第二次就是将每次走的起点和集合中已有的作比较,移除掉已经存在的,剩下的就是仅在终点出现但是未在起点出现的地点,即最终的终点.
*/
// public static String destCity(List<List<String>> paths) {
// Set a =new HashSet();
// for(List<String> path : paths){
// //将终点加入到集合中
// a.add(path.get(1));
// }
// for(List<String> path : paths){
// a.remove(path.get(0));
// }
// return (String)a.iterator().next();
// }
/**
* 解法二:
* 思路是创建一个Map集合,将每次走的起点和终点存入到map中,key是起点,value是终点,
* 接着在遍历每次走的路线,如果某次走的终点不是其他路线的起点,则该终点就是最终的终点.
* @param paths
* @return
*/
public static String destCity(List<List<String>> paths) {
Map<String,String> map = new HashMap<>();
for(List<String> path : paths){
map.put(path.get(0), path.get(1));
}
for(String key : map.keySet()){
String value = map.get(map.get(key));
if(value == null){
return map.get(key);
}
}
return null;
}
public static void main(String[] args) {
List<String> list1 = new LinkedList<>();
List<String> list2 = new LinkedList<>();
List<String> list3 = new LinkedList<>();
list1.add("London");
list1.add("New York");
list2.add("New York");
list2.add("Lima");
list3.add("Lima");
list3.add("Sao Paulo");
List<List<String>> aList = new LinkedList<>();
aList.add(list1);
aList.add(list2);
aList.add(list3);
System.out.println(destCity(aList));
}
}
方法一:

方法二:


浙公网安备 33010602011771号