【并查集】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 ( 2 n ) O(2^n) O(2n),常数较大的算法
  • 空间复杂度: O ( 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(n) O(n)

方法二:并查集


复杂度分析

  • 时间复杂度: O ( ) O() O()
  • 空间复杂度: O ( ) O() O()

你可能感兴趣的:(#,并查集)