leetcode数组--1、longest-consecutive-sequence(最长的连续元素序列的长度)

题目描述

 

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.

解题思路:使用hash表来保存数组中的每一个数,每次遍历到一个数的时候看往上找到所有连续的数最多有几个,往下找比他小的数最多有几个.为了避免连续的序列中的数重复查找,在找到一个相邻的数之后就把他从hash表中标记表示已经遍历过,也就是一个连续的序列只会被查找一次.因此时间复杂度为O(n).
注意点:本题不需要考虑存在重复的数的情况
 1 #include <iostream>
 2 #include <vector>
 3 //#include <unordered_map>
 4 #include<tr1/unordered_map>
 5 using namespace std;
 6 using std::tr1::unordered_map;
 7 class Solution {
 8 public:
 9     int longestConsecutive(vector<int> &num) {
10         int n = num.size();
11         int CurLength = 0;
12         int MaxLength = 0;
13         //使用hash表存储,unordered_map是无序的map
14         unordered_map<int,bool> res;
15         for(int i=0;i<n;i++)
16         {
17             res[num[i]] = false;//表示该值存储在hash表中,但是还未被查找使用
18         }
19         for(int i = 0;i < n;i++)
20         {
21             //如果已查找到该值则跳过,避免一个值多次查找,重复操作,保证最长的序列只遍历一遍
22             if(res[num[i]])
23             {
24                 continue;
25             }
26             else
27             {
28                 //以num[i]为中心左右扩张,直到不连续为止
29                 res[num[i]] = true;
30                 CurLength = 1;
31                 //向右扩张
32                 for(int j = num[i] + 1;res.find(j) != res.end();j++)
33                 {
34                     CurLength ++;
35                     res[j] = true;
36                 }
37                 //向左扩张
38                 for(int j = num[i] - 1;res.find(j) != res.end();j--)
39                 {
40                     CurLength ++;
41                     res[j] = true;
42                 }
43                 //更新最大长度
44                 if(CurLength > MaxLength)
45                 {
46                     MaxLength = CurLength;
47                 }
48             }
49         }
50         return MaxLength;
51     }
52 };
53 int main()
54 {
55     int result;
56     Solution solution;
57     vector<int> vec;
58     vec.push_back(100);
59     vec.push_back(4);
60     vec.push_back(200);
61     vec.push_back(1);
62     vec.push_back(3);
63     vec.push_back(2);
64 
65     result = solution.longestConsecutive(vec);
66     cout<<result<<endl;
67     return 0;
68 }

 

posted @ 2017-06-08 10:59  qqky  阅读(172)  评论(0编辑  收藏  举报