[LeetCode] 128. Longest Consecutive Sequence Java

题目:

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.

题意及分析:一个数组中连续的元素序列的长度。

用一个set来查找,首先第一次遍历数组将数组添加到set中,去除重复元素,第二次对数组中的每个数查找其最长的连续串,然后将遍历过的数从set中移除。这样每个数都被遍历了两次,时间复杂度为o(n).

代码:

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();

        for(int i=0;i<nums.length;i++){
            set.add(nums[i]);       //保持nums[i]中数的唯一性
        }
        int max = 0;
        for(int i=0;i<nums.length;i++){
            if(set.contains(nums[i])){
                int count = 1;
                set.remove(nums[i]);

                int low = nums[i]-1;
                while(set.contains(low)){
                    count++;
                    set.remove(low);
                    low--;
                }

                int high = nums[i]+1;
                while(set.contains(high)){
                    count++;
                    set.remove(high);
                    high++;
                }
                max = Math.max(max,count);
            }
        }
        return max;
    }
}

 

转载于:https://www.cnblogs.com/271934Liao/p/7709761.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值