题目连接
https://leetcode.com/problems/longest-consecutive-sequence/
Longest Consecutive Sequence
Description
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.
class Solution { private: typedef vector<int> vec; typedef unordered_map<int, bool> UMAP; public: int longestConsecutive(vec &nums) { if(nums.empty()) return 0; UMAP vis; int ans = 0; for(auto &r: nums) vis[r] = false; for(auto &r: nums) { if(vis[r]) continue; int ret = 1; vis[r] = true; for(int j = r + 1; vis.find(j) != vis.end(); j++) { vis[j] = true; ret++; } for(int j = r - 1; vis.find(j) != vis.end(); j--) { vis[j] = true; ret++; } ans = max(ans, ret); } return ans; } };