题目描述:
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.
解题思路:
面试过程中,若面试官给出题后,应该先问清题意,比如本题,返回的是结果数组还是结果的长度,因为我面试过程中,面试官给我写的结果是[1,2,3,4]这个list.确认一下数组中是否存在重复的 元素,如果存在重复的元素呢?
另外,如果对时间复杂度有提示的话,若要求是o(nlogn)内,则可以通过排序来求解,但是要求是o(n),所以只能想别的办法,譬如时间换空间,双指针啥的。
在面试过程中,面试官问我,若存在重复的元素,你的代码要怎么处理它?这就会提示到我们可能需要使用HashSet来对元素进行去重。
我们可以将数组元素放入HashSet当中,根据连续序列的特点,一个连续序列,它的左右两边肯定是比它大1的数,如果不是,说明不满足连续。
所以我们可以根据这个特点从前往后遍历数组,并初始化该元素的左右边界,分别为left=n-1,right=n+1,然后再循环判断数组中是否存在left,right,直到不存在,则停止循环,此时就可以得出当前元素为中心的最大左右边界,我们通过边界就可以得到子序列的长度,并将它跟目前最大的子序列长度值进行比较,若比它大,则对最大子序列长度进行更新。
最后如果set在我们循环判断左右边界的时候已经被全部移除,为空了,我们就返回此时的最大长度。否则,遍历完数组的所有元素后,返回最大长度。
实现:
import java.util.HashSet;
class Solution {
public int longestConsecutive(int[] nums) {
if(nums==null||nums.length==0) return 0;
HashSet<Integer> set=new HashSet<>();
for(int num:nums){
set.add(num);
}
int maxLen=0;
for(int num:nums){
int left=num-1;
int right=num+1;
while(set.remove(left)) left--;
while(set.remove(right)) right++;
maxLen=Math.max(maxLen,right-left-1);
if(set.isEmpty()) return maxLen;
}
return maxLen;
}
}