力扣HOT100-最长连续序列

思路

常规的暴力解法是 对于数组中的每个元素x,都去检查数组中是否存在x+1,x+2···以及x-1,x-2···

那么假设数组中存在x+1,那么当我们检查x+1时,需要重复检查x+2···是否存在数组当中。而且,显然区间长度一定小于x为起点的区间。

即对于任意元素y,如果y-1存在于数组中,则跳过该元素。

只有y-1不存在于数组中的y才有可能是最长区间的起点。

所以我们可以用哈希表对这类元素进行跳过。

Python版本

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        d = set()
        for num in nums:
            d.add(num)
        res = 0
        for num in nums:
            if num - 1 in d:
                continue
            else:
                # 以num为起点的最长区间长度
                length = 1
                while True:
                    if num + 1 in d:
                        length+=1
                        num += 1
                    else:
                        break
                if length > res:
                    res = length
        return res

Java版本

class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> numSet = new HashSet<Integer>();
        for (int num : nums){
            numSet.add(num);
        }
        int res = 0;
        for (int num:nums){
            if (numSet.contains(num-1)){
                continue;
            }
            else{
                int len = 1;
                while (true){
                    if(numSet.contains(num+1)){
                        len++;
                        num++;
                    }
                    else{
                        break;
                    }
                }
                if (len > res){
                    res = len;
                }
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值