注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
10分钟前的新鲜面经, 一个湾湾小哥面的,在doordash待了三年半了已经。
题目比较有意思,感觉是小哥自己出的题, 有点类似简易版的word ladder II
题目大概就是说, doordash 送餐有几条路线, 让你求出从a 到b的最短路径
给你一个list of tuples
Roa要自己import library 和写test case。 尽量多和面试官沟通 把test case过一遍就没问题。
顺便再po一下我的代码哈
- import java.util.*;
-
- class Solution {
-
- public static void main(String[] args) {
- Solution shortestPath = new Solution();
- Map<Integer, List<Integer>> map = new HashMap<>();
- map.put(0, Arrays.asList(1, 2, 1));
- map.put(1, Arrays.asList(2, 3, 1));
- map.put(2, Arrays.asList(3, 4, 1));
- map.put(3, Arrays.asList(4, 5, 1));
- map.put(4, Arrays.asList(5, 1, 3));
- map.put(5, Arrays.asList(1, 3, 2));
- map.put(6, Arrays.asList(5, 3, 1));
-
- List<Integer> cities = Arrays.asList(1, 2, 3, 4, 5);
-
- boolean[] res = shortestPath.shortestPath(map, cities);
-
- for (boolean used : res) {
- System.out.println(used + ", ");
- }
- }
-
- // given a map of bidrectional routes
- // find a shortest path
- public boolean[] shortestPath(Map<Integer, List<Integer>> map, List<Integer> cities) {
- // 1 (1, 2, 1)
- // 1 -> [2, 1, 1]
- Map<Integer, List<int[]>> graph = new HashMap<>();
-
- for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
- int road = entry.getKey();
- List<Integer> value = entry.getValue();
- int from = value.get(0);
- int to = value.get(1);
- int weight = value.get(2);
-
- graph.computeIfAbsent(from, k -> new ArrayList<>()).add(new int[]{to, weight, road});
- graph.computeIfAbsent(to, k -> new ArrayList<>()).add(new int[]{from, weight, road});
- }
-
- // [city_id, sumOfWeight]
- PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
- Set<Integer> visited = new HashSet<>();
- pq.offer(new int[]{cities.get(0), 0});
- int targetCity = cities.get(cities.size() - 1);
- int lowestWeight = 0;
-
- while (!pq.isEmpty()) {
- int[] entry = pq.poll();
-
- if (entry[0] == targetCity) {
- lowestWeight = entry[1];
- break;
- }
-
- visited.add(entry[0]);
-
- for (int[] neis : graph.get(entry[0])) {
- if (!visited.contains(neis[0])) {
- pq.offer(new int[]{neis[0], entry[1] + neis[1]});
- }
- }
- }
-
- boolean[] res = new boolean[map.size()];
-
- dfs(cities.get(0), targetCity, graph, lowestWeight, res, new HashSet<>());
- return res;
- }
-
- private void dfs(int from, int target, Map<Integer, List<int[]>> graph, int weight, boolean[] res, Set<Integer> roads) {
- if (weight < 0) {
- return;
- }
-
- if (from == target) {
- for (int road : roads) {
- res[road] = true;
- }
- }
-
- for (int[] neis : graph.get(from)) {
- // add the road
- if (!roads.contains(neis[2])) {
- roads.add(neis[2]);
- dfs(neis[0], target, graph, weight - neis[1], res, roads);
- roads.remove(neis[2]);
- }
- }
- }
- }
复制代码
|