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

【哈希表】Longest Consecutive Sequence

时间:2015-04-06 17:22:41      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:c++   程序员   面试   哈希表   

题目:leetcode

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.


分析:

用一个哈希表,记录一个数是否已经被遍历,避免重复。

leetcode的测试用例没有考虑输入数组包含int类型最大最小值的问题。如输入[0x7fffffff,0x80000000],理应返回1,但如果没有考虑int类型最大最小值的问题,会返回2(即认为 0x7fffffff和0x80000000是两个相邻的数)。


int longestConsecutive(vector<int> &num) {
        if(num.size()<=1)
        return num.size();
        
        unordered_map<int,bool> n;
        for(auto &i:num)
        {
            n[i]=false;
        }
        int res=1;
        for(int i=0;i<num.size();i++)
        {
            if(n[num[i]]==true)
            continue;
            int length=1;
            if(num[i]!=0x80000000)
            {
                
                int number=num[i]-1;
                while(n.find(number)!=n.end())
                {
                    n[number]=true;
                    number--;
                    length++;
                    if(number==0x80000000)
                    break;
                }
                
            }
            if(num[i]!=0x7fffffff)
            {
                int number=num[i]+1;
                while(n.find(number)!=n.end())
                {
                    n[number]=true;
                    number++;
                    length++;
                    if(number==0x7fffffff)
                    break;
                }
            }
            res=max(res,length);
            
        }
        return res;
    }


【哈希表】Longest Consecutive Sequence

标签:c++   程序员   面试   哈希表   

原文地址:http://blog.csdn.net/bupt8846/article/details/44902777

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