LeetCode Longest Consecutive Sequence

来源:互联网 发布:淘宝网民族风棉麻棉裤 编辑:程序博客网 时间:2024/06/04 23:21

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)的时间复杂度,因此先排序,再顺序找最长连续这种思路不可行,因为基于比较的排序算法最低时间复杂度是O(nlongn).要想得到O(n)的时间复杂度,需要结合着题的特点,从图的角度思考。可以把数组看成图的结点,连续数字之间存在边,然后进行DFS搜索找到最长的路径。具体做法是,首先把所有数字放入一个hashset,如此可以在常数时间获取一个数以及判定一个数是否存在。然后试图从set中的每个数字开始,向两边搜索相邻的数字,搜索过的数字从set中删除,记录当前搜索的连续子串的长度,并且用maxLen来贪心的保存最大子串长度。如此操作,直到set为空。时间复杂度是O(n)(建set和删除 扫描两次所有元素),空间复杂度也是O(n)。

AC Code

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class Solution {  
  2.     public int longestConsecutive(int[] num) {  
  3.         //0241  
  4.         if(num == null || num.length == 0return 0;  
  5.         Set<Integer> set = new HashSet<Integer>();  
  6.         for(int n : num){  
  7.             set.add(n);  
  8.         }  
  9.         int maxLen = 0;  
  10.         while(!set.isEmpty()){  
  11.             Iterator iter = set.iterator();  
  12.             int curItem = (int) iter.next();  
  13.             int tempCur = curItem;  
  14.             int len = 0;  
  15.             while(set.contains(curItem)){  
  16.                 len++;  
  17.                 set.remove(curItem);  
  18.                 curItem--;  
  19.             }  
  20.             curItem = tempCur + 1;  
  21.             while(set.contains(curItem)){  
  22.                 len++;  
  23.                 set.remove(curItem);  
  24.                 curItem++;  
  25.             }  
  26.             if(len > maxLen) maxLen = len;  
  27.         }  
  28.         return maxLen;  
  29.         //0249  
  30.     }  
  31. }  
0 0