(Leetcode) Longest Consecutive Sequence (Hard)

Posted ollie-lin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(Leetcode) Longest Consecutive Sequence (Hard)相关的知识,希望对你有一定的参考价值。

題目:

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 };    

 

以上是关于(Leetcode) Longest Consecutive Sequence (Hard)的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix