128. 最长连续序列
This commit is contained in:
21
test003.cpp
Normal file
21
test003.cpp
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
int longestConsecutive(vector<int>& nums) {
|
||||||
|
unordered_map <int, int> data;
|
||||||
|
for(int x:nums) data[x] = 1;
|
||||||
|
int res = 0;
|
||||||
|
for(auto &n:data){
|
||||||
|
if(n.second){
|
||||||
|
int val = n.first; int len = 1;
|
||||||
|
for(int i = 1; data.count(val - i)&&data[val - i]; i++){
|
||||||
|
data[val - i] = 0; len++;
|
||||||
|
}
|
||||||
|
for(int i = 1; data.count(val + i)&&data[val + i]; i++){
|
||||||
|
data[val + i] = 0; len++;
|
||||||
|
}
|
||||||
|
res = max(len, res);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user