128. Longest Consecutive Sequence
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.
求最长连续序列的长度
C++:
1 class Solution { 2 private: 3 unordered_map<int,int> cntMap ; 4 public: 5 int longestConsecutive(vector<int>& nums) { 6 int res = 0 ; 7 for(int num : nums){ 8 cntMap[num] = 1 ; 9 } 10 for(int num : nums){ 11 forward(num) ; 12 } 13 for(int num : nums){ 14 res = max(res,cntMap[num]) ; 15 } 16 return res ; 17 } 18 19 int forward(int num){ 20 if (cntMap.count(num) == 0){ 21 return 0 ; 22 } 23 int cnt = cntMap[num] ; 24 if (cnt > 1) 25 return cnt ; 26 27 cnt = forward(num+1) + 1 ; 28 cntMap[num] = cnt ; 29 return cnt ; 30 } 31 };