Longest Consecutive Sequence
Q:
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.
A:
先遍历一遍,使用hash_map存储所有的数字,并把所有的value初始化为0,value在后续计算最长连续数字的时候会用到。
重新遍历一遍,计算以当前数字为尾的最长连续数字的长度,如果value非0直接跳过,表示该数字已经使用过,否则查看该数字-1对应的数字是否在hash_map中,如果在,加上该数字对应的value即可。说的不是很清楚,直接贴代码,很容易看懂。
class Solution { public: int longestConsecutive(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function unordered_map<int, int> conse_num; for (int i = 0; i < num.size(); ++i) { conse_num[num[i]] = 0; } int max_conse = 0; for (int i = 0; i < num.size(); ++i) { if (conse_num[num[i]] != 0) continue; int cur = num[i]; int pre = cur - 1; conse_num[cur] = 1; while (conse_num.find(pre) != conse_num.end()) { if (conse_num[pre] != 0) { conse_num[cur] += conse_num[pre]; break; } else { conse_num[pre] = 1; conse_num[cur]++; pre--; } } max_conse = max(max_conse, conse_num[cur]); } return max_conse; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号