Leetcode128——Longest Consecutive Sequence

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

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.

2. 求解

题中明确要求时间复杂度为O(n),因此这道题肯定不能使用循环遍历。这道题主要是考察哈希表,因为哈希表每次查询的时间复杂度为O(1)。因此首先要将数组转为Map。然后分别查询每个数字的前一个数与后一个数,统计数字连续的数量。如果在哈希表中存在相邻的数,查询后应该从哈希表中删除,当然不删也可以。如果哈希表为空,则直接跳出循环,不再遍历。

public class Solution {
    public int longestConsecutive(int[] nums) {
        int max = 0;
        int count = 0;
        Map<String, Integer> map = new HashMap<String, Integer>();
        for(int i = 0; i < nums.length; i++) {
            map.put(String.valueOf(nums[i]), nums[i]);
        }
        for(int i = 0; i < nums.length; i++) {
            count = 1;
            int x = nums[i];
            while(true) {
                int temp = --x;
                if(map.containsKey(String.valueOf(temp))) {
                    map.remove(String.valueOf(temp));
                    count++;
                }else {
                    break;
                }
            }
            //必须重置x
            x = nums[i];
            while(true) {
                int temp = ++x;
                if(map.containsKey(String.valueOf(temp))) {
                    map.remove(String.valueOf(temp));
                    count++;
                }else {
                    break;
                }
            }
            if(count > max) {
                max = count;
            }
            if(map.isEmpty()) {
                break;
            }
        }
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值