zoukankan      html  css  js  c++  java
  • 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.

    思路:

    先是定义一个unordered_set,把数组里面原来的数值插入进去,之后再设立一个循环,从当前的一个数开始,也可以从当前数下一个数值开始,就看你怎么设置这个初始值count了。循环里面的循环每一次如果能够找到,count+1,并且删除集合里面的数值。这样,在大循环里面不会有影响的。

    程序一开始出错的原因在于没有设立一个res,无法进行更新。所以没有AC。

    代码:

    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            int len=nums.size();
            unordered_set<int> mp;
            for(int i=0;i<len;i++){
                mp.insert(nums[i]);
            }
            int res=0;
            
            for(int i=0;i<len;i++){
                int count=1;
                for(int j=nums[i]+1;mp.find(j)!=mp.end();j++){
                    count++;
                    mp.erase(j);
                }
                
                for(int j=nums[i]-1;mp.find(j)!=mp.end();j--){
                    count++;
                    mp.erase(j);
                }
                res=max(res,count);
                if(mp.size()<1) break;
            }
            
            return res;
        }
    };


  • 相关阅读:
    BUAA OO Unit1 表达式求导
    中介者模式
    命令模式
    观察者模式
    解释器模式
    策略模式
    迭代器模式
    模板方法模式
    代理模式
    桥接模式
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519861.html
Copyright © 2011-2022 走看看