標籤:style blog http color os io 資料 for
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,0,0,1,2.本以為重複就不算聯絡,答案應該是3,結果是4。你妹的
坑2:允許負數,這個沒考慮實在不應該。
坑3:大數可能是Integer.MIN_VALUE,因此用計數排序的時候要注意考慮溢出
演算法思路:
思路1:計數排序;線性排序演算法,再求出最長連續序列長度。
沒有做到bug-free,因此不貼了。
思路2:發散法,遇到一個數字,則想兩端發散,並維護最大長度。
1 public class Solution { 2 public int longestConsecutive(int[] num) { 3 if (num == null || num.length == 0) 4 return 0; 5 Set<Integer> set = new HashSet<Integer>(); 6 int max = 1; 7 for (int tem : num) { 8 set.add(tem); 9 }10 for (int tem : num) {11 if (set.contains(tem)) {12 set.remove(tem);13 int len = 1;14 int post = tem + 1;15 while (set.contains(post)) {16 set.remove(tem);17 post++;18 len++;19 max = Math.max(max, len);20 }21 int pre = tem - 1;22 while (set.contains(pre)) {23 set.remove(pre);24 pre--;25 len++;26 max = Math.max(max, len);27 }28 }29 }30 return max;31 }32 33 }
還可以用遞迴實現。大資料效率略低,不再實現了。時間、空間複雜度都是O(n)。