Skip to content

Instantly share code, notes, and snippets.

@phpmypython
Created December 23, 2014 19:32
Show Gist options
  • Select an option

  • Save phpmypython/0aff99a85ddff89cd638 to your computer and use it in GitHub Desktop.

Select an option

Save phpmypython/0aff99a85ddff89cd638 to your computer and use it in GitHub Desktop.
public int longestConsecutive(int[] num) {
int res = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int n : num) {
if (!map.containsKey(n)) {
int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0;
int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0;
// sum: length of the sequence n is in
int sum = left + right + 1;
map.put(n, sum);
// keep track of the max length
res = Math.max(res, sum);
// extend the length to the boundary(s)
// of the sequence
// will do nothing if n has no neighbors
map.put(n - left, sum);
map.put(n + right, sum);
}
else {
// duplicates
continue;
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment