8000 add an O(n) worst case time complexity solution to longest consecutiv… · xtao/leetcode@ffe3838 · GitHub
[go: up one dir, main page]

Skip to content
Sign in

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit ffe3838

Browse files
committed
add an O(n) worst case time complexity solution to longest consecutive sequence
1 parent c6a7e96 commit ffe3838

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)
0