|
| 1 | +// https://leetcode.com/problems/longest-consecutive-sequence |
| 2 | +// T: O(n) |
| 3 | +// S: O(n) |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +public class LongestConsecutiveSequence { |
| 11 | + private static class Node { |
| 12 | + Node next; |
| 13 | + Node previous; |
| 14 | + } |
| 15 | + |
| 16 | + public int longestConsecutive(int[] nums) { |
| 17 | + final Map<Integer, Node> nodes = createDisjointSets(nums); |
| 18 | + return longestConsecutiveSequenceLength(nodes); |
| 19 | + } |
| 20 | + |
| 21 | + private Map<Integer, Node> createDisjointSets(int[] array) { |
| 22 | + final Map<Integer, Node> result = new HashMap<>(); |
| 23 | + for (int element : array) { |
| 24 | + if (result.containsKey(element)) continue; |
| 25 | + |
| 26 | + Node current = new Node(); |
| 27 | + |
| 28 | + if (result.containsKey(element - 1)) { |
| 29 | + Node left = result.get(element - 1); |
| 30 | + left.next = current; |
| 31 | + current.previous = left; |
| 32 | + } |
| 33 | + |
| 34 | + if (result.containsKey(element + 1)) { |
| 35 | + Node right = result.get(element + 1); |
| 36 | + current.next = right; |
| 37 | + right.previous = current; |
| 38 | + } |
| 39 | + |
| 40 | + result.put(element, current); |
| 41 | + } |
| 42 | + |
| 43 | + return result; |
| 44 | + } |
| 45 | + |
| 46 | + private int longestConsecutiveSequenceLength(Map<Integer, Node> nodes) { |
| 47 | + final Set<Node> processedNodes = new HashSet<>(); |
| 48 | + int maxLength = 0; |
| 49 | + |
| 50 | + for (Node node : nodes.values()) { |
| 51 | + int length = getLength(node, processedNodes); |
| 52 | + maxLength = Math.max(maxLength, length); |
| 53 | + } |
| 54 | + |
| 55 | + return maxLength; |
| 56 | + } |
| 57 | + |
| 58 | + private int getLength(Node node, Set<Node> processedNodes) { |
| 59 | + if (node == null) return 0; |
| 60 | + if (processedNodes.contains(node)) return 0; |
| 61 | + processedNodes.add(node); |
| 62 | + return 1 + getLength(node.previous, processedNodes) + getLength(node.next, processedNodes); |
| 63 | + } |
| 64 | +} |
0 commit comments