[LeetCode] 128. Longest Consecutive Sequence

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

Your algorithm should run in O(n) complexity.

Example:

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.


题意:给一个未排序数组,找出其中最长的连续串,要求复杂度O(n)
其实题目给了半个提示,未排序,但是要求的复杂度又是O(n)级别的。由于这个是个纯乱序数组,而且没有什么特色的数组
排序的话复杂度一定是O(nlogn)级别的,所以直接放弃排序
这题可以开一个set去记录出现了哪些数字,然后从我们开始的某一点去向两边访问,如果有这个数字,就删除,然后不断维护长度就行了。
举例:
100, 3, 200, 1, 4, 2
如果我们访问到了3,对其左右两边进行寻找,发现了1,2,4,然后这些数字就没必要再去访问了,因为他们可能产生的结果已经通过3解掉了
class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums.length == 0)
            return 0;
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            set.add(nums[i]);
        }
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i])) {
                int len = 1; // 这个是因为我懒,这个变量可以不要,通过r和l就能计算了
                int r = nums[i] + 1;
                int l = nums[i] - 1;
                while(set.contains(r)) {
                    set.remove(new Integer(r));
                    r ++;
                    len ++;
                }
                while(set.contains(l)) {
                    set.remove(new Integer(l));
                    l --;
                    len ++;
                }
                max = Math.max(len, max);
            }
        }
        return max;
    }
}
 
原文地址:https://www.cnblogs.com/Moriarty-cx/p/9864931.html