One Java solution
\tpublic int longestConsecutive(int[] num) {\n        Set set = new HashSet(num.length);\n        for (int n: num) {\n        \tset.add(n);\n        }\n        
\tpublic int longestConsecutive(int[] num) {\n        Set<Integer> set = new HashSet<Integer>(num.length);\n        for (int n: num) {\n        \tset.add(n);\n        }\n        \n        int maxLength = 0;\n        for (int n: num) {\n        \tif (set.contains(n)) {\n        \t\tint length = 1;\n            \tint next = n - 1;\n            \twhile (set.contains(next)) {\n            \t\tlength++;\n            \t\tset.remove(next);\n            \t\tnext--;\n            \t}\n            \tnext = n+1;\n            \twhile (set.contains(next)) {\n            \t\tlength++;\n            \t\tset.remove(next);\n            \t\tnext++;\n            \t}\n            \t\n            \tif (length > maxLength) {\n            \t\tmaxLength = length;\n            \t}\n        \t}\n        }\n        \n        return maxLength;\n\t}\n\nThe basic idea is put all integers into a set. Iterate all the integers and for every integer try to find its consecutive numbers in the set and accumulate the length. The trick is remove the integer whenever it has been visited, which makes the process O(n) because every integer will only be visited once.
[]