LeetCode Longest Consecutive Sequence


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

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

题意:给出一个数组,求最长的连续序列,要求时间复杂度O(n)

思路:主要是用到hash,在遍历一个数时,先递减,看是否在hash中找得到,然后再递增,看是否在hash中找得到,这样就可以计算出连续序列的长度,同时更新最大值。

代码如下:

class Solution
{
    public int longestConsecutive(int[] nums)
    {
        Set<Integer> hs = new HashSet<Integer>();
        for (int n : nums) hs.add(n);

        int ans = 0;
        for (int num : nums)
        {
            if (hs.remove(num))
            {
                int len = 1;
                int val = num;
                while (hs.remove(val - 1)) val--;
                len += num - val;

                val = num;
                while (hs.remove(val + 1)) val++;
                len +=  val - num;

                ans = Math.max(ans, len);
            }
        }

        return ans;
    }
}

你可能感兴趣的:(LeetCode Longest Consecutive Sequence)