Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 6, 2017 14:40
Show Gist options
  • Save shailrshah/0e4e0164c321b930b5e5f51f890d36f4 to your computer and use it in GitHub Desktop.
Save shailrshah/0e4e0164c321b930b5e5f51f890d36f4 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.
public int longestConsecutive(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
int max = 0;
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i]))
continue;
int left = map.getOrDefault(nums[i]-1, 0);
int right = map.getOrDefault(nums[i]+1, 0);
int sum = left + right + 1;
max = Math.max(max, sum);
map.put(nums[i] - left, sum);
map.put(nums[i] + right, sum);
map.put(nums[i], sum);
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment