leetcode题解-128. Longest Consecutive Sequence

题目:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

本题是想要寻找一个数组中最长的连续序列。有几个点需要注意的是:1,数组未排序;2,可能存在重复数字。我看到题目第一个想到的是先将数组进行排序,这样我们可以方便的找到连续的数字。思路很简单,代码入下:

    public int longestConsecutive(int[] nums) {
        if(nums.length == 0 || nums == null)
            return 0;
        if(nums.length == 1)
            return 1;
        Arrays.sort(nums);
        int max = 0, tmp = 1;
        for(int i=0; i<nums.length-1; i++){
            if (nums[i] == nums[i+1] - 1 || nums[i] == nums[i+1]){
                if (nums[i] == nums[i+1] - 1)
                    tmp ++;
            }else{
                max = Math.max(max, tmp);
                tmp = 1;
            }
        }
        return Math.max(max, tmp);
    }

这种方法击败了96%的用户,很惊呀,然后去看了下discuss,发现原来别人都是用hashSet或者HashMap去做,然后找了一个效率相对比较高的程序,可以击败86%的用户。代码入下:

    public int longestConsecutive1(int[] nums) {

        Set<Integer> set = new HashSet<>();
        //先将数组中的每个数添加到set中,实现去重;
        for(int n: nums) set.add(n);

        int max = 0;

        //接下来遍历数组
        for(int n: nums){
            int count = 0;
            //如果set已经空,则返回;
            if(set.isEmpty()) break;

            //对于数组中的数,将其左右相连的数都remove掉,这样set会越来越小
            int val = n;
            while(set.remove(val--))
                count ++;

            val = n;
            while(set.remove(++val))
                count ++;
            //判断完每个连续的数块,就更新一次最大值
            max = Math.max(count,max);
        }

        return max;

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值