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
.
Your algorithm should run in O(n) complexity.
public class Solution { public int longestConsecutive(int[] num) { // Start typing your Java solution below // DO NOT write main() function Set<Integer> set = new HashSet<Integer>(); // mistake1 int max = 0; for(int s:num){ set.add(s); } for(int s:num){ int left = s-1; int right = s+1; int count = 1; while(set.contains(left)){ set.remove(left); left--;//check left concestive numbers // mistake2 count++; } while(set.contains(right)){ set.remove(right); right++;//check right concestive numbers count++; } if(max < count) max = count; // max = max <count ? count: max; } return max; } }