标签:
题目链接:https://leetcode.com/problems/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、-1是否在数组中,如果遍历数组来查找显然时间复杂度要大于O(n),考虑用HashSet可以方便的知道一个元素是否在集合中,如果一个元素+1/-1都不在集合中,则删去该元素,并且每一个元素判断后都删除,则时间复杂度为O(n)。
算法:
【Leetcode】Longest Consecutive Sequence
标签:
原文地址:http://blog.csdn.net/yeqiuzs/article/details/51628546