@@ -409,6 +409,47 @@ \subsubsection{代码}
409
409
};
410
410
\end {Code }
411
411
412
+ \subsubsection {分析2 }
413
+ 第一直觉是个聚类的操作,应该有union,find的操作.连续序列可以用两端和长度来表示.
414
+ 本来用两端就可以表示,但考虑到查询的需求,将两端分别暴露出来.用\fn {unordered_map<int, int> map}来
415
+ 存储.原始思路来自于\url {http://discuss.leetcode.com/questions/1070/longest-consecutive-sequence}
416
+
417
+ \subsubsection {代码 }
418
+
419
+ \begin {Code }
420
+ // Leet Code, Longest Consecutive Sequence
421
+ // 时间复杂度O(n),空间复杂度O(n)
422
+ // Author: @advancedxy
423
+ class Solution {
424
+ public:
425
+ int longestConsecutive(vector<int> &num) {
426
+ unordered_map<int, int> map;
427
+ int size = num.size();
428
+ int l = 1;
429
+ for (int i = 0; i < size; i++) {
430
+ if (map.find(num[i]) != map.end()) continue;
431
+ map[num[i]] = 1;
432
+ if (map.find(num[i] - 1) != map.end()) {
433
+ l = max(l, mergeCluster(map, num[i] - 1, num[i]));
434
+ }
435
+ if (map.find(num[i] + 1) != map.end()) {
436
+ l = max(l, mergeCluster(map, num[i], num[i] + 1));
437
+ }
438
+ }
439
+ return size == 0 ? 0 : l;
440
+ }
441
+
442
+ private:
443
+ int mergeCluster(unordered_map<int, int> &map, int left, int right) {
444
+ int upper = right + map[right] - 1;
445
+ int lower = left - map[left] + 1;
446
+ int length = upper - lower + 1;
447
+ map[upper] = length;
448
+ map[lower] = length;
449
+ return length;
450
+ }
451
+ };
452
+ \end {Code }
412
453
413
454
\subsubsection {相关题目 }
414
455
\begindot
0 commit comments