陌陌笔试-Java研发工程师(商业化)
1.构建图使用递归和回溯实现最长路径
通过100%
public class Solution {
public String LongestBehaviorPath (String[] paths) {
Map<String,List<String>> graph = new HashMap<>();
Map<String,Integer> indegree = new HashMap<>();
for(String path : paths){
String []steps = path.split("->");
for(int i = 0;i<steps.length-1;i++){
graph.putIfAbsent(steps[i],new ArrayList<>());
graph.get(steps[i]).add(steps[i+1]);
indegree.put(steps[i+1],indegree.getOrDefault(steps[i+1],0)+1);
indegree.putIfAbsent(steps[i],0);
}
}
List<String> startNodes = new ArrayList<>();
for(String node:indegree.keySet()){
if(indegree.get(node) == 0){
startNodes.add(node);
}
}
List<String> longestPath = new ArrayList<>();
for(String start : startNodes){
dfs(start,new ArrayList<>(),graph,longestPath);
}
return String.join("->",longestPath);
}
private static void dfs(String node,List<String> path,Map<String,List<String>> graph,List<String> longestPath){
path.add(node);
if(path.size()> longestPath.size()){
longestPath.clear();
longestPath.addAll(new ArrayList<>(path));
}
if(graph.containsKey(node)){
for(String neighbor: graph.get(node)){
dfs(neighbor,path,graph,longestPath);
}
}
path.remove(path.size() - 1);
}
}
2.求逆值对
双重for循环遍历比较
通过100%
通过100%
public class Solution {
public String LongestBehaviorPath (String[] paths) {
Map<String,List<String>> graph = new HashMap<>();
Map<String,Integer> indegree = new HashMap<>();
for(String path : paths){
String []steps = path.split("->");
for(int i = 0;i<steps.length-1;i++){
graph.putIfAbsent(steps[i],new ArrayList<>());
graph.get(steps[i]).add(steps[i+1]);
indegree.put(steps[i+1],indegree.getOrDefault(steps[i+1],0)+1);
indegree.putIfAbsent(steps[i],0);
}
}
List<String> startNodes = new ArrayList<>();
for(String node:indegree.keySet()){
if(indegree.get(node) == 0){
startNodes.add(node);
}
}
List<String> longestPath = new ArrayList<>();
for(String start : startNodes){
dfs(start,new ArrayList<>(),graph,longestPath);
}
return String.join("->",longestPath);
}
private static void dfs(String node,List<String> path,Map<String,List<String>> graph,List<String> longestPath){
path.add(node);
if(path.size()> longestPath.size()){
longestPath.clear();
longestPath.addAll(new ArrayList<>(path));
}
if(graph.containsKey(node)){
for(String neighbor: graph.get(node)){
dfs(neighbor,path,graph,longestPath);
}
}
path.remove(path.size() - 1);
}
}
2.求逆值对
双重for循环遍历比较
通过100%
全部评论
双重for都能解决吗
我也这题,感觉好简单😅
相关推荐
点赞 评论 收藏
分享
05-05 12:57
门头沟学院 前端工程师
记着呢:说的很对,已经工作近7年,就是觉得年轻的时候太多忧虑,没有好好玩一玩,虽然现在我也是很多忧心事,但是真的感觉年轻的时光才是最宝贵的,玩的开心,做自己喜欢的事,全力以赴,这才是应该做的 点赞 评论 收藏
分享
