码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Longest Consecutive Sequence

时间:2014-07-22 23:16:14      阅读:408      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   使用   

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.

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

mamicode.com,码迷
 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 };
mamicode.com,码迷

 

[Leetcode] Longest Consecutive Sequence,码迷,mamicode.com

[Leetcode] Longest Consecutive Sequence

标签:style   blog   http   java   color   使用   

原文地址:http://www.cnblogs.com/easonliu/p/3699679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!