LeetCode – Longest Consecutive Sequence (Java)
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2]
, the longest consecutive elements sequence should be [1, 2, 3, 4]
. Its length is 4.
Your algorithm should run in O(n) complexity.
Java Solution 1
Because it requires O(n) complexity, we can not solve the problem by sorting the array first. Sorting takes at least O(nlogn) time.
We can use a HashSet to add and remove elements. The add, remove and contains methods have constant time complexity O(1).
public int longestConsecutive(int[] nums) { HashSet<Integer> set = new HashSet<>(); for(int num: nums) set.add(num); int result = 0; for(int num: nums){ int count = 1; int down = num1; while(set.contains(down)){ set.remove(down); down; count++; } int up = num+1; while(set.contains(up)){ set.remove(up); up++; count++; } result = Math.max(result, count); } return result; } 
Java Solution 2
We can also project the arrays to a new array with length to be the largest element in the array. Then iterate over the array and get the longest consecutive sequence. If the largest number is very large, then the time complexity would be bad.
<pre><code> String foo = "bar"; </code></pre>

alexwest11

Subham Kuamr

Ujvári Bálint

Ujvári Bálint

alexwest11

Tin

aravindbuddha

Jesus Ledesma

Elior Malul

Elior Malul

sarthak sehgal

Anita CT

Anita CT

sarthak sehgal

k3vi

k3vi

Aashish Kalia

kayal

ryanlr

Wang Shuhao

rupalph

Vaibhav Gupta

Matias SM

Matias SM

Eugene Arnatovich

Renzo Nuccitelli

Renzo Nuccitelli

animesh

animesh

coder

dawei su

Vimukthi Weerasiri

ygw

Tony Wang

PK

PK

rs

Aaron Zhang

Paul Sun

ryanlr

ryanlr

ryanlr

Mo

cj

Dun Liu

violethaze

Wellwisher