LeetCode——最长连续序列

Q:给定一个无序的整数类型数组,求最长的连续元素序列的长度。
例如:
给出的数组为[100, 4, 200, 1, 3, 2],
最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
你需要给出时间复杂度在O(n)之内的算法
A:
用hash表来解决这个问题,先初始化一个hash表, 存储所有数组元素, 然后遍历这个数组, 对找到的数组元素, 去搜索其相连的上下两个元素是否在hash表中, 如果在, 删除相应元素并增加此次查找的数据长度, 如果不在, 从下一个元素出发查找。已经访问过的元素记录下来或者删除,因为访问过的长度已经知道了。

    public int longestConsecutive(int[] num) {
        if (num.length == 0)
            return 0;
        HashMap<Integer, Boolean> map = new HashMap<>();
        for (int value : num) {
            map.put(value, true);
        }
        int max = 0;
        for (int i = 0; i < num.length; i++) {
            if (!map.get(num[i]))
                continue;
            else {
                map.put(num[i], false);
                int r = num[i] + 1;
                int l = num[i] - 1;
                while (map.containsKey(r)) {
                    map.put(r, false);
                    r++;
                }
                while (map.containsKey(l)) {
                    map.put(l, false);
                    l--;
                }
                max = Integer.max(r - l - 1, max);
            }
        }
        return max;
    }
原文地址:https://www.cnblogs.com/xym4869/p/12492263.html