Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/6207346 to your computer and use it in GitHub Desktop.
Save charlespunk/6207346 to your computer and use it in GitHub Desktop.
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 is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
import java.util.HashMap;
public class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < num.length; i++){
int n = num[i];
if(map.containsKey(n)) continue;
if(map.containsKey(n - 1) || map.containsKey(n + 1)){
int value = 1;
int beforeOffset = 0;
if(map.containsKey(n - 1)){
beforeOffset = map.get(n - 1);
value += map.get(n - 1);
map.put(n - beforeOffset, value);
map.put(n, value);
}
if(map.containsKey(n + 1)){
value += map.get(n + 1);
map.put(n + map.get(n + 1), value);
map.put(n, value);
}
if(map.containsKey(n - 1)) map.put(n - beforeOffset, value);
}
else map.put(n, 1);
}
int max = 0;
for(Integer len: map.values()){
if(len > max) max = len;
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment