• 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.

    小疑问:为什么map的迭代器没有重载+操作符,而只能自加或者自减

    解决:1.因为vector支持通过元素位置实现随机访问,所以他的迭代器可以进行算术运算。map不可以。

    2.对于vector等支持随机访问的效果上没有差别,但是这两者的意义不同,一般的容器都重载了迭代器的++ --操作符,但如果容器不支持元素位置的随机访

    问(此时重载的++意思是指向下一个元素,但这个元素的物理位置不一定和当前相连),是不可以进行迭代器的算术操作的(+n操作)。


    代码:

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            if(num.size()==0) return 0;
            map<int,bool> m;
            for(int i=0;i<num.size();++i){
                m[num[i]]=1;
            }
            int res=1;
            int tempRes=1;
            map<int,bool>::iterator it=m.begin();
            map<int,bool>::iterator end=--m.end();
            while(it!=end)
            {
                if(abs((it->first-(++it)->first))==1){
                    ++tempRes;
                }else{
                    if(tempRes>res) res=tempRes;
                    tempRes=1;
                }
            }
            if(tempRes>res) res=tempRes;
            return res;
        }
    };
  • 相关阅读:
    sprint2第一天任务完成情况
    第七天完成任务
    第六天任务情况
    第五天任务完成情况
    第四天任务完成情况
    第三天任务完成情况
    第二天任务完成情况
    第一天任务完成情况
    组队开发项目NABCD分析
    网络设置-指定ip
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4221455.html
Copyright © 2020-2023  润新知