[LeetCode] Longest Consecutive Sequence 求解

題目

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

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.數組

Your algorithm should run in O(n) complexity.code

思路

  • (預處理)保存一個哈希表(或者集合),用於o(1)時間查找該數字是否存在於數組當中element

  • 數字有可能重複,因此其實哈希集合就夠了,典型的空間換時間get

  • (預處理)一個表徵是否使用的used表,用於o(1)時間查找該數字是否已經被包含在另一個序列當中it

  • 注意數字有多是負數,因此直接用數組很差io

  • 輪詢數組,遇到一個數字,查找其左,右的最長連續序列長度,並記錄與已知最大長度相比較class

代碼

public class Solution {
    public int longestConsecutive(int[] num) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < num.length; i++) {
            map.put(num[i], i);
        }

        Map<Integer, Boolean> used = new HashMap<Integer, Boolean>();
        for (int i : num) {
            used.put(i, false);
        }

        int max = Integer.MIN_VALUE;
        for (int i = 0; i < num.length; i++) {
            if (!used.get(num[i])) {
                used.put(num[i], true);

                int k = num[i];

                int leftLength = findLength(k, map, "left");
                int rightLength = findLength(k, map, "right");

                // mark used
                for (int j = 0; j < leftLength; j++) {
                    used.put(k - j - 1, true);
                }
                for (int j = 0; j < rightLength; j++) {
                    used.put(k + j + 1, true);
                }

                int total = leftLength + rightLength + 1;
                if (total > max) {
                    max = total;
                }

            }
        }
        return max;
    }

    private int findLength(int k, Map<Integer, Integer> map, String direction) {
        if ("left".equals(direction)) {
            int l = k - 1;
            while (map.containsKey(l)) {
                l -= 1;
            }
            return k - l - 1;
        } else {
            int l = k + 1;
            while (map.containsKey(l)) {
                l += 1;
            }
            return l - k - 1;
        }
    }
}
相關文章
相關標籤/搜索