You are viewing a single comment's thread. Return to all comments →
ugly but working Java solution:
Map<Integer, Set<Integer>> index = new HashMap<>(); int[] steps = new int[queries.length]; int max = 0; int i = 0; for (int[] query : queries) { int a = query[0]; int b = query[1]; Set<Integer> leftGraph = index.get(a); Set<Integer> rightGraph = index.get(b); if(leftGraph == null && rightGraph == null) { Set<Integer> n = new HashSet<>(); n.add(a); n.add(b); index.put(a, n); index.put(b, n); max = Math.max(max, n.size()); } else if(leftGraph == null) { rightGraph.add(a); index.put(a, rightGraph); max = Math.max(max, rightGraph.size()); } else if(rightGraph == null) { leftGraph.add(b); index.put(b, leftGraph); max = Math.max(max, leftGraph.size()); } else { if(leftGraph == rightGraph) { leftGraph.add(a); leftGraph.add(b); index.put(a, leftGraph); index.put(b, leftGraph); max = Math.max(max, leftGraph.size()); } else { // merge if(leftGraph.size() > rightGraph.size()) { leftGraph.addAll(rightGraph); index.put(b, leftGraph); for (Integer v : rightGraph) { index.put(v, leftGraph); } max = Math.max(max, leftGraph.size()); } else { rightGraph.addAll(leftGraph); index.put(b, rightGraph); for (Integer v : leftGraph) { index.put(v, rightGraph); } max = Math.max(max, rightGraph.size()); } } } steps[i] = max; i++; } return steps;
Seems like cookies are disabled on this browser, please enable them to open this website
Friend Circle Queries
You are viewing a single comment's thread. Return to all comments →
ugly but working Java solution: