【並查集】A007_LC_最長連續序列(記憶化搜索 / 並查集 (代辦))

一、Problem

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

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

二、Solution

方法一:map + dfs

這是最粗暴的做法…

class Solution {
    Set<Integer> st = new HashSet<>();
    public int longestConsecutive(int[] A) {
        for (int i : A) 
            st.add(i);
        int max = 0;
        for (int i : A)
            max = Math.max(max, dfs(i));
        return max;
    }
    int dfs(int i) {
        int len = 1;
        if (st.contains(i+1))
            len += dfs(i+1);
        return len;
    }
}

複雜度分析

  • 時間複雜度:O(2n)O(2^n),常數較大的算法
  • 空間複雜度:O(n)O(n)

我們發現在 dfs 中會有許多重複的搜搜,比如 A[1,2,3,4],從 1 開始搜索的時候,搜索到 4 後,途中經過 2,3,然後從 1 開始的搜索結束後,從 2 開始又會經過 3、4,這些應該在第一次搜索就應該緩存下來。

class Solution {
    Set<Integer> st;
    Map<Integer, Integer> m;
    public int longestConsecutive(int[] A) {
        st = new HashSet<>();
        m = new HashMap<>();
        for (int i : A) 
            st.add(i);
        int max = 0;
        for (int i : A)
            max = Math.max(max, dfs(i));
        return max;
    }
    int dfs(int i) {
        if (m.getOrDefault(i+1, 0) > 0)
            return m.get(i+1);
        int len = 1;
        if (st.contains(i+1))
            len += dfs(i+1);
        m.put(i+1, len);
        return len;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

方法二:並查集


複雜度分析

  • 時間複雜度:O()O()
  • 空間複雜度:O()O()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章