【两次过】Lintcode 124. 最长连续序列

给定一个未排序的整数数组,找出最长连续序列的长度。

样例

给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4

说明

要求你的算法复杂度为O(n)


解题思路:

由于算法复杂度要求,可以使用空间换时间。将所有数字都存入HashSet中,再遍历数组,从遍历的元素向两边扩展搜索,看看有无连续序列。

public class Solution {
    /**
     * @param num: A list of integers
     * @return: An integer
     */
    public int longestConsecutive(int[] num) {
        // write your code here
        Set<Integer> set = new HashSet<>();
        for(int i=0; i<num.length; i++)
            set.add(num[i]);
        
        int res = 0;
        
        for(int i=0; i<num.length; i++){
            int tmp1 = num[i] - 1;
            int l = 0;  //记录其左边有多少连续数
            while(set.contains(tmp1)){
                set.remove(tmp1);
                l++;
                tmp1--;
            }
            
            int tmp2 = num[i] + 1;
            int r = 0;  //记录其右边有多少连续数
            while(set.contains(tmp2)){
                set.remove(tmp2);
                r++;
                tmp2++;
            }
            
            res = Math.max(res, l + r + 1);
        }
        
        return res;
    }
}

二刷,注意需要遍历的时候删除元素,这样才能避免很多无谓的重复,时间复杂度才是O(n)

public class Solution {
    /**
     * @param num: A list of integers
     * @return: An integer
     */
    public int longestConsecutive(int[] num) {
        // write your code here
        Set<Integer> set = new HashSet<>();
        for(int i : num)
            set.add(i);
        
        int res = 1;
        for(int i : num){
            int temp = 1;
            
            for(int j=i-1; set.contains(j); j--){
                set.remove(j);
                temp++;
            }
                
            for(int j=i+1; set.contains(j); j++){
                set.remove(j);
                temp++;
            }
                
            res = Math.max(res, temp);
        }
        
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值