-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDestination city.java
More file actions
54 lines (45 loc) · 1.29 KB
/
Destination city.java
File metadata and controls
54 lines (45 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//using Hashmap
class Solution {
public String destCity(List<List<String>> paths) {
Map<String,String> hmap = new HashMap<>();
int i=0;
while(i<paths.size()){
List<String> currentList = paths.get(i);
hmap.put(currentList.get(0),currentList.get(1));
i++;
}
String destination = paths.get(0).get(1);
while(hmap.containsKey(destination)){
destination = hmap.get(destination);
}
return destination;
}
}
//using hashset
class Solution {
public String destCity(List<List<String>> paths) {
HashSet<String> srcCities = new HashSet<>();
for(List<String> path: paths) {
srcCities.add(path.get(0));
}
for(List<String> path: paths) {
// check if every dest city has src city
if(!srcCities.contains(path.get(1))) {
return path.get(1);
}
}
return "";
}
}
//brute-force approach
class Solution {
public String destCity(List<List<String>> paths) {
String startes="";
for(int i=0;i<paths.size();i++)
startes+=paths.get(i).get(0);
for(int i=0;i<paths.size();i++)
if(!startes.contains(paths.get(i).get(1)))
return paths.get(i).get(1);
return null;
}
}