Leecode128

Leecode128

使用hashset解决
空间复杂度O(n),额外使用了hashset存储
事件复杂度O(n),内层循环中数组里每个数仅仅遍历了一次

import java.util.HashSet;

public class Solution2 {
    public static void main(String[] args) {
        int[] nums = {100, 4, 200, 1, 3, 2};
        int i = new Solution2().longestConsecutive(nums);
        System.out.println(i);
    }

    public int longestConsecutive(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        //使用set存储不重复的数字集合用于下方判断数字是否存在于数组中
        HashSet<Integer> set = new HashSet<Integer>();
        for (int num : nums) {
            set.add(num);
        }

        int res = 0;

        //事件复杂度为1,每个数字仅仅在内部循环中被访问一遍
        for (int i = 0; i < nums.length; i++) {
            //如果存在比当前数字小1的数字则跳过这个数,知道访问到没有比当前数字小1的数字
            if(set.contains(nums[i] - 1))
                continue;

            int t = nums[i];
            int count = 1;

            //计算当前连续序列的长度
            while(set.contains(t + 1)){
                count++;
                t = t + 1;
            }
            res = res > count ? res : count;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值