128.最长连续序列

LeetCode参考:https://leetcode.cn/problems/longest-consecutive-sequence/

算法设计思路

问题的关键在于要求时间复杂度为 O ( n ) \Omicron(n) O(n),我们知道基于比较的排序算法时间复杂度下界为 O ( n log ⁡ n ) \Omicron(n \log n) O(nlogn),时间为线性的排序算法对于数据都有一定要求。

算法步骤:

  • 数组中可能含有相同的元素,考虑使用HashSet去重
  • 依次遍历HashSet中的所有元素,
    • 判断否是从连续序列的首位开始,如果不是说明压根不是最长的序列;如果是才继续执行下面的代码;
      • 判断HashSet中是否包含连续的序列,直到其跳出循环;
      • 更新最长连续序列的长度;
  • 返回结果。
class Solution {
    public int longestConsecutive(int[] nums) {
        // set去重
        Set<Integer> set = new HashSet<Integer>();
        for (int num : nums) {
            set.add(num);
        }
        
        int longestLen = 0; // 最长连续序列的长度
        for (int i : set) {
            if (!set.contains(i - 1)) { // 是否是从连续序列的首位开始,如果不是说明压根不是最长的序列
                int currentLen = 1; // 记录当前连续系列长度
                int currentNum = i; // 记录当前连续序列数字

                while (set.contains(currentNum + 1)) {
                    currentLen++;
                    currentNum++;
                }
                longestLen = Math.max(longestLen, currentLen); // 更新最长连续序列的长度
            }
        }
        return longestLen;
    }
}
posted @ 2023-09-22 16:57  gengduc  阅读(5)  评论(0编辑  收藏  举报  来源