LeetCode-128. Longest Consecutive Sequence

来源:互联网 发布:himall2.6官方版源码 编辑:程序博客网 时间:2024/06/09 14:57

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),而数组又是无序的,说明不能先对数组进行排序处理,那么我们可以考虑空间换时间的思路,借助额外的空间来减少时间复杂度。

方法一

因为数组中会存在重复的数字,而重复的数字不对结果造成任何影响,于是我们可以选用set集合去除重复数字。
对于数组中的每个数,首先要排除重复搜索的可能,然后再在哈希表中寻找是否存在它的下一位数,如果存在则一直找下去,期间不断更新长度。
时间复杂度:O(n)

class Solution {    public int longestConsecutive(int[] nums) {        if(nums.length==0)            return 0;        Set<Integer> numSet=new HashSet<>();        for(int i=0;i<nums.length;++i)        {            numSet.add(nums[i]);        }        int longestLength=1;        for(int i=0;i<nums.length;++i)        {            if(!numSet.contains(nums[i]-1))            {                int longestLengthTemp=1;                int findNum=nums[i]+1;                while(numSet.contains(findNum))                {                    longestLengthTemp++;                    findNum++;                }                longestLength=Math.max(longestLength,longestLengthTemp);            }        }        return longestLength;    }}

方法二

这是时间复杂度不满足要求的解法,但在官网也可以通过。
先将数组由小到大排序,当两个数不相等时再判断它们是否是连续的数,如果是则增加长度,如果不是则将长度暂存值重置为1。
因为有排序,所以时间复杂度为O(nlgn)。

class Solution {    public int longestConsecutive(int[] nums) {        if(nums.length==0)            return 0;        Arrays.sort(nums);        int longestLengthTemp=1;        int longestLength=1;        for(int i=1;i<nums.length;++i)        {            if(nums[i]!=nums[i-1])            {                if(nums[i]==nums[i-1]+1)                {                    longestLengthTemp++;                }                else                {                    longestLengthTemp=1;                }            }            longestLength=Math.max(longestLength,longestLengthTemp);        }        return longestLength;    }}
原创粉丝点击