Leetcode:128. 最长连续序列

Leetcode:128. 最长连续序列

题目描述

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

思路

思路1 排序+遍历

在对数组进行排序后,依次遍历计算最长的连续序列,注意相等情况

思路2 hash表+初始值才遍历

使用一个hash表记录数组中存在的数字,每次都只计算当前数字在且该数字减一不在(避免重复遍历),然后依次叠加计算最长连续序列

代码

代码1

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        
        Arrays.sort(nums);
        int result = 1;
        int temp = 1;
        for(int i = 1; i < nums.length; i++){
            if (nums[i] - nums[i - 1] == 1){
                temp += 1;
                if (temp > result){
                    result = temp;
                }
            }else if(nums[i] != nums[i - 1]){
                temp = 1; 
            }
        }
        
        return result;
    }
}

代码2

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        int result = 1;
        int temp = 1;
        
        HashSet numSet = new HashSet<>();
        for(int num: nums){
            numSet.add(num);
        }
        
        for(int num: nums){
            if (!numSet.contains(num - 1)){
                temp = 1;
                while (numSet.contains(num + 1)){
                    temp += 1;
                    num ++;
                }
                if (temp > result){
                    result = temp;
                }
            }
        }
        return result;
    }
}

复杂度分析

思路1时间复杂度

$O(nlog(n))$

思路1空间复杂度

$O(n)$若看作排序需要n的空间

思路2时间复杂度

$O(n)$

思路2空间复杂度

$O(n)$


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:198. 打家劫舍 Leetcode:198. 打家劫舍
Leetcode:198. 打家劫舍题目描述你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个
2020-04-22
下一篇 
Leetcode:124. 二叉树中的最大路径和 Leetcode:124. 二叉树中的最大路径和
Leetcode:124. 二叉树中的最大路径和题目描述给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。 示例 1:输入: [1,2,3
2020-04-22
  目录