LeetCode热题100——最长连续序列(3)

题目链接:https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-100-liked

哈希

先使用哈希表HashSet去重,然后遍历哈希表,如果有比当前元素小1的存在,则跳过,如果没有,就开始匹配,看最长能匹配到多少

class Solution {
    public int longestConsecutive(int[] nums) {
        //使用HashSet去重
        Set<Integer> set = new HashSet<Integer>();
        //哈希表存储数据
        for(int num : nums){
            set.add(num);
        }
        //存储答案
        int cnt = 0;
        //遍历哈希表
        for(int num : set){
            //如果不存比当前数小1的,那就继续执行,否则就跳过
            if(!set.contains(num - 1)){
                //当前数
                int curnum = num;
                //当前长度
                int curcnt = 1;
                
                //循环判断,如果存在比当前数大1的,就继续执行
                while(set.contains(curnum + 1)){
                    //当前数加1
                    curnum++;
                    //当前长度加1
                    curcnt++;
                }
                //取最长的长度
                cnt = Math.max(cnt, curcnt);
            }
        }
        return cnt;
    }
}

还剩97题!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值