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.

使用容器实现。已经判断过的不用再次判断。

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int> &num) {
 4         map<int, int> mp;
 5         for (int i = 0; i < num.size(); ++i) {
 6             mp[num[i]] = 1;
 7         }
 8         int len = 0, tmp;
 9         for (int i = 0; i < num.size(); ++i) {
10             tmp = 1;
11             if (mp[num[i]] == 1) {
12                 int left = num[i] - 1;
13                 while (mp.count(left) && mp[left] == 1) {
14                     mp[left--] = 0;
15                     ++tmp;
16                 }
17                 int right = num[i] + 1;
18                 while (mp.count(right) && mp[right] == 1) {
19                     mp[right++] = 0;
20                     ++tmp;
21                 }
22                 len = (len > tmp) ? len : tmp;
23             }
24         }
25         return len;
26     }
27 };

 

相关文章:

  • 2021-12-08
  • 2021-10-15
  • 2022-12-23
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-16
猜你喜欢
  • 2021-09-03
  • 2021-10-12
  • 2021-11-14
  • 2021-07-07
  • 2021-08-01
相关资源
相似解决方案