#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/*
由于可能有负整数,所以用数组不太合适。
用hashmap,c++用unordered_set的接口,
保证时间复杂度为O(n)。
遍历一次nums里的元素,如果哈希表里面有的话就找到它的相邻元素
并把它删掉,避免下次重复重复计算。这样的话每次一找就找的是连续
一串数。
*/
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> myset;
for (int i = 0; i < nums.size(); i++) {
myset.insert(nums[i]);
}
int max = 0;
while (!myset.empty()) {
int start = *myset.begin();
int counter = 1;
myset.erase(start);
int left = start - 1, right = start + 1;
while (myset.find(left) != myset.end()) {
myset.erase(left);
counter++;
left--;
}
while (myset.find(right) != myset.end()) {
myset.erase(right);
counter++;
right++;
}
if (counter > max) {
max = counter;
}
}
return max;
}
};
int main(int argc, const char * argv[]) {
vector<int> myvec = {100, 4, 200, 1, 3, 2};
Solution s;
cout << s.longestConsecutive(myvec) << endl;
return 0;
}
leetcode-128-Longest Consecutive Sequence
最新推荐文章于 2022-03-06 23:29:26 发布