【重点】【哈希】128.最长连续序列

文章介绍了如何使用Java和Python在LeetCode问题中解决最长连续序列问题,通过HashSet数据结构找到并更新最长连续序列长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
思路:https://leetcode.cn/problems/longest-consecutive-sequence/solutions/2362995/javapython3cha-xi-biao-ding-wei-mei-ge-l-xk4c/?envType=study-plan-v2&envId=top-100-liked
在这里插入图片描述

Python

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        hash_set = set(nums)
        max_len = 0
        for item in hash_set:
            if item - 1 not in hash_set: # 必须用set, 否则会超时
                tmp_val = item
                while tmp_val + 1 in hash_set:
                    tmp_val += 1
                max_len = max(max_len, tmp_val - item + 1)
        return max_len

Java

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int len = 0, maxLen = 0, tmp;
        for (int num : set) {
            tmp = num;
            if (!set.contains(num - 1)) { // 序列起点
                len = 1;
                while (set.contains(++tmp)) {
                    ++len;
                }
                maxLen = maxLen > len ? maxLen : len;
            }
        }

        return maxLen;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值