Hard题
问题描述
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.
问题分析
其实想到了类似的思路,但是没有打通。
构建一个map,用这个map保存包含当前值的最长连续串的长度。每次新读入一个数据x时,要看x-1和x+1是否存在,如果存在,则加上两边的长度。具体看代码中的注释吧~
AC代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> m;
int max = 0;
for (int i = 0; i < nums.size(); i++){
int num = nums[i];
if (m.find(num) == m.end()){
int left = 0;
int right = 0;
if (m.find(num-1) != m.end())
left = m[num-1];
if (m.find(num+1) != m.end())
right = m[num+1];
//下面三行是关键。不用将当前串中所有最长值都改变,只要将边界改变即可!
m[num] = left + 1 + right;
m[num-left] = m[num];
m[num+right] = m[num];
if (m[num] > max)
max = m[num];
}
}
return max;
}
};
网友评论