给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
进阶:你可以设计并实现时间复杂度为 O(n) 的解决方案吗?

示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence

解法一 排序

不建议这么写。

解法二 集合

分析

先用Set去重,然后遍历set,如果num-1不在集合中,说明num是起始位置,再循环判断num+1是否在集合中,更新当前序列的长度,直到num+1不在集合时,再更新最大序列长度。如果num-1在集合中,说明num不是起始位置,则跳过。

代码

  1. class Solution {
  2. public int longestConsecutive(int[] nums) {
  3. if(nums==null||nums.length==0) return 0;
  4. Set<Integer> set = new HashSet<Integer>();
  5. for(int num: nums){
  6. set.add(num);
  7. }
  8. int maxLen = 1;
  9. for(int num: set){
  10. if(!set.contains(num-1)){
  11. int curNum = num;
  12. int curLen = 1;
  13. while(set.contains(curNum+1)){
  14. curLen++;
  15. curNum++;
  16. }
  17. maxLen = Math.max(maxLen, curLen);
  18. }
  19. }
  20. return maxLen;
  21. }
  22. }