Created
November 6, 2017 14:40
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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