Skip to content

Commit ebb384b

Browse files
committed
Merge pull request soulmachine#12 from advancedxy/master
为longest consecutive sequence增加了一个worst case为O(n)的解法
2 parents eafa918 + acf9f5e commit ebb384b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

C++/chapLinearList.tex

+41
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,47 @@ \subsubsection{代码}
409409
};
410410
\end{Code}
411411

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}
412453

413454
\subsubsection{相关题目}
414455
\begindot

0 commit comments

Comments
 (0)