@@ -0,0 +1,1281 @@
+package set;%0A%0Aimport java.util.HashSet;%0Aimport java.util.Set;%0A%0A/**%0A * https://oj.leetcode.com/problems/longest-consecutive-sequence/%0A * %3Cp/%3E%0A * Given an unsorted array of integers, find the length of the longest consecutive elements sequence.%0A * For example,%0A * Given %5B100, 4, 200, 1, 3, 2%5D,%0A * The longest consecutive elements sequence is %5B1, 2, 3, 4%5D. Return its length: 4.%0A * Your algorithm should run in O(n) complexity.%0A */%0Apublic class LongestConsecutiveSequence %7B%0A    public int longestConsecutive(int%5B%5D num) %7B%0A        int l = num == null ? 0 : num.length;%0A        if (l %3C= 1) return l;%0A%0A        Set%3CInteger%3E set = new HashSet%3C%3E();%0A        for (int i = 0; i %3C l; i++) %7B%0A            set.add(num%5Bi%5D);%0A        %7D%0A%0A        int max = 0;%0A        for (int i = 0; i %3C l; i++) %7B%0A            if (!set.contains(num%5Bi%5D)) continue;%0A%0A            int count = 1;%0A            int value = num%5Bi%5D + 1;%0A            while (set.contains(value)) %7B%0A                set.remove(value);%0A                value++;%0A                count++;%0A            %7D%0A            value = num%5Bi%5D - 1;%0A            while (set.contains(value)) %7B%0A                set.remove(value);%0A                value--;%0A                count++;%0A            %7D%0A            max = Math.max(count, max);%0A        %7D%0A        return max;%0A    %7D%0A%7D%0A

longest consecutive sequence