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.

题意很清晰,从一个无序数组中找到最长的连续序列。

最开始想用treeset,set.ceiling、set.floor可以帮助查找相邻元素,时间复杂度O(nlgn)。但是要求时间复杂度O(n),排序的话只能用bucketsort,但是bucket怎么分,解决不了。

其实没有这么复杂,关键点在于,根据一个元素去找他的相邻元素时,相邻元素是确定的。当前元素是t,那么他的相邻元素只能是t-1、t+1,所以用set就可以。

 

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

        int longestStreak = 0;

        for (int num : num_set) {
            if (!num_set.contains(num-1)) {//之前没有在连续队列中
                int currentNum = num;
                int currentStreak = 1;

                while (num_set.contains(currentNum+1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}

对于每个元素,如果他没有在连续队列里,那么就以他为开始,尝试去构建一个连续队列。举个栗子:

Input: [100, 4, 200, 1, 3, 2]

100:set中没有99,那么尝试以100为开始,构建连续队列。但是没有101,所以跳过。

4:set中有3,跳过。

200:同100。

1:set中没有0,那么尝试以1为开始,构建连续队列。1,2,3,4。长度为4。

3:同4。

2:同4。

所以你看,虽然for循环中包含一个while循环,但是时间复杂度仍然是O(n)。对于input中的元素,只有1执行了while循环,循环的元素为2、3、4,对于2、3、4,他们就没有再执行while循环了。

所以while循环只会执行最多n次,总体的时间复杂度是O(n)+O(n),还是O(n)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值