題目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Code
1 class Solution 2 { 3 public: 4 int longestConsecutive(vector<int>& nums) 5 { 6 /* input : 1 2 3 6 5 4 */ 7 /* solution1 Hashtable */ 8 unordered_map<int, int> h; 9 for (auto num : nums) //num get nums element 10 { 11 if (h.count(num)) 12 continue; 13 auto it_l = h.find(num - 1); 14 auto it_r = h.find(num + 1); 15 16 int l = it_l != h.end() ? it_l->second : 0; 17 int r = it_r != h.end() ? it_r->second : 0; 18 19 20 auto it_end = h.end(); 21 if (l > 0 && r > 0) 22 h[num] = h[num - l] = h[num + r] = l + r + 1; 23 else if (l > 0) 24 h[num] = h[num - l] = l + 1; 25 else if (r > 0) 26 h[num] = h[num + r] = r + 1; 27 else 28 h[num] = 1; 29 } 30 31 int ans = 0; 32 for (const auto& kv : h) 33 ans = max(ans, kv.second); 34 return ans; 35 } 36 };
原文地址:https://www.cnblogs.com/ollie-lin/p/8971391.html
时间: 2024-10-11 05:59:20