Skip to content

Instantly share code, notes, and snippets.

@jporcelli
Created October 19, 2014 03:02
Show Gist options
  • Save jporcelli/88d29088a0532c7ffb25 to your computer and use it in GitHub Desktop.
Save jporcelli/88d29088a0532c7ffb25 to your computer and use it in GitHub Desktop.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
public static int longestConsecutive(int[] num) {
//need support for concurrent modifications of the backing table
//@todo find a different way of removing entries from the table during iteration
Map<String, Set<Integer>> h = new ConcurrentHashMap<String, Set<Integer>>();
int max = Integer.MIN_VALUE;
//init the table
for(int v : num){
String sv = String.valueOf(v);
if(!h.containsKey(sv)){
Set<Integer> p = new HashSet<Integer>();
p.add(v);
h.put(sv, p);
}
}
for(Entry<String, Set<Integer>> e : h.entrySet()){
Integer k = null;
int x = Integer.valueOf(e.getKey());
//partition
Set<Integer> p1 = e.getValue();
int n = x + 1;
String y = String.valueOf(n);
if(h.containsKey(y)){
//partition
Set<Integer> p2 = h.get(y);
//union partitions
p1.addAll(p2);
h.put(y, p1);
p1 = h.get(y);
k = p1.size();
if(k!= null && k > max){
max = k;
}
h.remove(y);
x = n;
n++;
y = String.valueOf(n);
//go through the entire contiguous sequence from x
//and union the partitions
while(h.containsKey(y)){
p2 = h.get(y);
p1.addAll(p2);
h.put(y, p1);
p1 = h.get(y);
k = p1.size();
if(k!= null && k > max){
max = k;
}
h.remove(y);
x = n;
n++;
y = String.valueOf(n);
}
}else if(p1.size() > max){
max = p1.size();
}
}
return max;
}
@jporcelli
Copy link
Author

use a set instead of map, hashset. Backed by hash table same as hashmap

@jporcelli
Copy link
Author

note the passing of the reference is key if only using successor values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment