前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Longest Consecutive Sequence

Longest Consecutive Sequence

作者头像
Tyan
发布2019-05-25 23:10:38
5170
发布2019-05-25 23:10:38
举报
文章被收录于专栏:SnailTyanSnailTyan

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。然后分别查询每个数字的前一个数与后一个数,统计数字连续的数量。如果在哈希表中存在相邻的数,查询后应该从哈希表中删除,当然不删也可以。如果哈希表为空,则直接跳出循环,不再遍历。

代码语言:javascript
复制
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;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年03月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 问题描述
  • 2. 求解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档