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)的时间复杂度,因此先排序,再顺序找最长连续这种思路不可行,因为基于比较的排序算法最低时间复杂度是O(nlongn).要想得到O(n)的时间复杂度,需要结合着题的特点,从图的角度思考。可以把数组看成图的结点,连续数字之间存在边,然后进行DFS搜索找到最长的路径。具体做法是,首先把所有数字放入一个hashset,如此可以在常数时间获取一个数以及判定一个数是否存在。然后试图从set中的每个数字开始,向两边搜索相邻的数字,搜索过的数字从set中删除,记录当前搜索的连续子串的长度,并且用maxLen来贪心的保存最大子串长度。如此操作,直到set为空。时间复杂度是O(n)(建set和删除 扫描两次所有元素),空间复杂度也是O(n)。

AC Code

public class Solution {
    public int longestConsecutive(int[] num) {
        //0241
        if(num == null || num.length == 0) return 0;
        Set<Integer> set = new HashSet<Integer>();
        for(int n : num){
            set.add(n);
        }
        int maxLen = 0;
        while(!set.isEmpty()){
            Iterator iter = set.iterator();
            int curItem = (int) iter.next();
            int tempCur = curItem;
            int len = 0;
            while(set.contains(curItem)){
                len++;
                set.remove(curItem);
                curItem--;
            }
            curItem = tempCur + 1;
            while(set.contains(curItem)){
                len++;
                set.remove(curItem);
                curItem++;
            }
            if(len > maxLen) maxLen = len;
        }
        return maxLen;
        //0249
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值