LeetCode 128 Longest Consecutive Sequence (C++, Python)
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
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.
Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Solution { public: int longestConsecutive(vector<int> &num) { unordered_set<int> graph; for (int i = 0; i < num.size(); ++i) { graph.insert(num[i]); } int len = 0; while (!graph.empty()) { auto it = graph.begin(); int tmplen = 1; auto less = graph.find(*it - 1); while (less != graph.end()) { tmplen ++; auto tmp = graph.find(*less - 1); graph.erase(less); less = tmp; } auto more = graph.find(*it + 1); while (more != graph.end()) { tmplen ++; auto tmp = graph.find(*more + 1); graph.erase(more); more = tmp; } len = max(len, tmplen); graph.erase(it); } return len; } }; |
Solution Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution: # @param num, a list of integer # @return an integer def longestConsecutive(self, num): graph = set() for i in num: graph.add(i) clen = 0 while graph: v = graph.pop() tmplen = 1 less = v - 1 while less in graph: tmplen += 1 graph.remove(less) less -= 1 more = v + 1 while more in graph: tmplen += 1 graph.remove(more) more += 1 clen = max(clen, tmplen) return clen |