Created
December 23, 2014 19:32
-
-
Save phpmypython/0aff99a85ddff89cd638 to your computer and use it in GitHub Desktop.
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[] 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