问题描述:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
源码:
感觉最近进了“红区”,题目难度都不小。这题我看了第一眼就想用map,但是搞半天,怎么搞都有重复的部分。后来在Discuss区看到了一个大佬用的,每次执行的是st[item-left]而不是st[item-1],解决了问题。时间79%,空间100%。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int n = nums.size(), result = 0;
if(n==0) return result;
unordered_map<int, int> st;
for(auto item: nums){
if(st.count(item)) continue;
int left=0, right=0;
if(st.count(item-1)) left = st[item-1];
if(st.count(item+1)) right = st[item+1];
if(left>0 && right==0){
st[item] = 1+left;
st[item-left] = 1+left;
}
else if(left==0 && right>0){
st[item] = 1+right;
st[item+right] = 1+right;
}
else if(left>0 && right>0){
st[item] = 1+left+right;
st[item-left] = 1+left+right;;
st[item+right] = 1+left+right;;
}
else{
st[item] = 1;
}
result = max(result, st[item]);
}
return result;
}
};