這道題中要求時間複雜度爲O(n),首先咱們能夠知道的是,若是先對數組排序再計算其最長連續序列的時間複雜度是O(nlogn),因此不能用排序的方法。我一開始想是否是應該用動態規劃來解,發現其並不符合動態規劃的特徵。最後採用相似於LRU_Cache中出現的數據結構(集快速查詢和順序遍歷兩大優勢於一身)來解決問題。具體來講其數據結構是HashMap<Integer,LNode>,key是數組中的元素,全部連續的元素能夠經過LNode的next指針相連起來。html
整體思路是,順序遍歷輸入的數組元素,對每一個元素先看下HashMap的key中是否已經有這個元素,若是有則無需作任何事情,若是有,再看下這個元素的左鄰居也就是比它小1的元素是否在,若是在的話把左鄰居的LNodel的next指針指到當前這個元素的LNode,而後再看右鄰居的元素是否存在hashmap中,若是在,則把當前指針的next指到右鄰居節點上,經過反覆這樣的操做,最後全部連續的sequece的LNode都被連在一塊兒。node
以後再計算哪一個連續的鏈表長度最長。數組
下面是AC代碼:數據結構
1 class LNode{ 2 int ele; 3 LNode next; 4 public LNode(int _ele){ 5 ele = _ele; 6 } 7 }
1 /** 2 * Longest Consecutive Sequence 3 * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 4 * O(n) 5 * @param num 6 * @return 7 */ 8 public int longestConsecutive(int[] num){ 9 //the most important data structure; 10 HashMap<Integer,LNode> kv = new HashMap<Integer,LNode>(num.length); 11 int max = 0; 12 for(int n: num){ 13 if(!kv.containsKey(n)){ 14 LNode l = new LNode(n); 15 if(kv.containsKey(n-1)) 16 kv.get(n-1).next = l; 17 if(kv.containsKey(n+1)) 18 l.next = kv.get(n+1); 19 kv.put(n, l); 20 } 21 } 22 Iterator<LNode> it = kv.values().iterator(); 23 //k is used to keep tracking those node who has been caculated in other sequences 24 //it is to reduce the time complexity, to insure the O(n) time complexity 25 HashMap<Integer,LNode> k = new HashMap<Integer,LNode>(); 26 27 while(it.hasNext()) 28 { 29 LNode temp = it.next(); 30 if(!k.containsKey(temp.ele)) 31 { 32 int nu = 1; 33 while(temp.next!=null){ 34 temp = temp.next; 35 k.put(temp.ele, temp); 36 //kv.remove(temp.ele); 37 nu++; 38 } 39 if(nu>max) 40 max = nu; 41 } 42 } 43 return max; 44 }