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

leetcode || 128、Longest Consecutive Sequence

时间:2015-04-28 09:38:52      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:leetcode   hashtable   

problem:

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.

Hide Tags
 Array
题意:在乱序数组中寻找最长的连续子序列(没有顺序要求)

thinking:

(1)要求时间复杂度为O(n),只能使用hashtable了。

(2)unordered_map底层就是用hashtable实现的,可以拿来当做hashtable使用

code:

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        unordered_map<int,int> hashtable;
        for(int i = 0;i < num.size();i++) {
            if(hashtable.find(num[i]) != hashtable.end())
                continue;
            int minus_1 = num[i] - 1;
            int plus_1 = num[i] + 1;
            unordered_map<int,int>::iterator minus_1iter,plus_1iter;
            minus_1iter = hashtable.find(minus_1);
            plus_1iter = hashtable.find(plus_1);
            if(minus_1iter != hashtable.end() && plus_1iter != hashtable.end()) {
                hashtable[num[i]] = hashtable[minus_1] + hashtable[plus_1] + 1;
                hashtable[num[i] - hashtable[minus_1]] = hashtable[num[i]];
                hashtable[num[i] + hashtable[plus_1]] = hashtable[num[i]];
            }
            else if(minus_1iter == hashtable.end() && plus_1iter == hashtable.end()) {
                hashtable[num[i]] = 1;
            }
            else if(minus_1iter != hashtable.end()) {
                hashtable[num[i]] = hashtable[minus_1] + 1;
                hashtable[num[i] - hashtable[minus_1]] = hashtable[num[i]];
            }
            else {
                hashtable[num[i]] = hashtable[plus_1] + 1;
                hashtable[num[i] + hashtable[plus_1]] = hashtable[num[i]];
            }
        }
         
        //find the maxlen
        int ans = INT_MIN;
        for(unordered_map<int,int>::iterator iter = hashtable.begin();iter != hashtable.end();++iter) {
            if(iter->second > ans)
                ans = iter->second;
        }
        return ans;
    }
};


leetcode || 128、Longest Consecutive Sequence

标签:leetcode   hashtable   

原文地址:http://blog.csdn.net/hustyangju/article/details/45331019

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