LeetCode开心刷题五十六天——128. Longest Consecutive Sequence

时间:2019-12-16 09:32:01   收藏:0   阅读:87

最近刷题进展尚可,但是形式变化了下,因为感觉眼睛会看瞎,所以好多写在纸上。本来想放到文件夹存储起来,但是太容易丢了,明天整理下,赶紧拍上来把

今晚是周末,这一周都在不停的学学学,我想下周怕是不能睡午觉了,中午回去床对我的诱惑太大了,我得想办法,一进门先把被褥收起来,再放个欢快的歌,中午少吃点,加油小可爱

之前欠下的烂帐,把太多简单题做完,导致剩下的都是难题,所以万万记住一点捷径都不要走
128看花花酱大神的解法,发现对hashtable的了解十分不足,甚至一些常见函数都不知道是干什么的
这道题涉及的知识点竟然还有并查集,逃来逃去没逃出去。
 
128. Longest Consecutive Sequence
Hard

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

BONUS:
auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_map<int,int> h;
        int ans=0;
        
        for(int num:nums){
            if(h.count(num)) continue;
            //check whether can find iterator
            auto it_l=h.find(num-1);
            auto it_r=h.find(num+1);
                
            int l=it_l!=h.end()?it_l->second:0;
            int r=it_r!=h.end()?it_r->second:0;
            int t=l+r+1;
            
            h[num]=h[num-l]=h[num+r]=t;
            
            ans=max(ans,t);
        }
        return ans;
    }
};

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!