Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
class Solution { public int longestConsecutive(int[] nums) { HashSet<Integer> set = new HashSet<Integer>(); for(int i : nums) set.add(i); int res = 0; for(int i: nums){ int len = 1; for(int j = i-1; set.contains(j); j--){ len++; set.remove(j); } for(int k = i+1; set.contains(k); k++){ len++; set.remove(k); } res = Math.max(len, res); } return res; } }
划重点!HashSet的查找的效率是O(1),所以加上遍历才能达到O(n)
思想是以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。
set.remove()也很关键,可以不要,但是会严重影响runtime。加上以后每记录一个数就删除,避免后续重复被cue