Longest Consecutive Sequence

来源:互联网 发布:网络法律咨询 编辑:程序博客网 时间:2024/06/06 13:18

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.


思路:这个是我看到的最容易理解的版本。

O(n)就说明不能用sort 的方法,sort的最高只能nlog(n);

解决的办法就是利用hashset 来用空间换时间,每个元素以增长的方式来进行扩充,然后算每段长度的len,用一个maxlen来update即可。

图解:元素是连续的,但是是断开的。

————   ———     ————————

用len的方式来算区间,算是这个题目的聪明之处。

public class Solution {    public int longestConsecutive(int[] nums) {        if(nums == null || nums.length == 0) return 0;        HashSet<Integer> hashset = new HashSet<Integer>();        for(Integer i: nums){            hashset.add(i);        }                int maxlen = 0;        for(Integer i: nums){            int left = i-1;            int right = i+1;            int len = 1;            while(hashset.contains(left)){                len++;                hashset.remove(left);                left--;            }            while(hashset.contains(right)){                len++;                hashset.remove(right);                right++;            }            maxlen = Math.max(maxlen, len);        }        return maxlen;    }}


0 0