限制时间复杂度为o(n),于是只能用哈希表
用一个哈希表存储所有出现过的元素,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度
class Solution
{public:int longestConsecutive(vector<int> &nums){unordered_set<int> setting;int longest = 0;for (int i = 0; i < nums.size(); i++){setting.insert(nums[i]);}for (auto i : nums){int length = 1;for (int j = i - 1; setting.find(j) != setting.end(); j--){setting.erase(j);++length;}for (int j = i + 1; setting.find(j) != setting.end(); j++){setting.erase(j);++length;}longest = max(longest, length);}return longest;}
};