zoukankan      html  css  js  c++  java
  • [leetcode]Longest Consecutive Sequence

    最近经常闲的无聊,于是就做做leetcode的题了,目测好像都不是很难.

    不过呢,闲的无聊还是记录下某些做了的题.

    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.

    一看呢,就是排序,然后找就好了,但是要求是O(n),排序明显是个O(n*logn)的算法.

    只是找连续的嘛,我们可以把所有的数字都存入hash表,然后随意从某个数字开始找他的前面和后面那个是否存在.

    然后得到一个最大的长度.当然找过的就可以删掉了...你想,一个连续的序列,你从中间任意位置开始往两边找不都一样么.

    所以只要找过就可以删掉了.

    class Solution {
    public:
        set<int> flag;
        int findBound(int n , bool asc){
            int ans = 0;
            set<int>::iterator iter;
            while((iter = flag.find(n)) != flag.end()){
                flag.erase(iter);
                ans ++;
                if(asc) n-- ; else n++;
            }
            return ans;
        }
        int longestConsecutive(vector<int> &num) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
                
            int ans = 0;
            flag.clear();
            for(int i = 0 ; i < num.size() ; i++)
               flag.insert(num[i]);
            for(int i = 0 ; i < num.size(); i++){
                ans = max(findBound(num[i],true) + findBound(num[i]+1,false) , ans); 
            }
            return ans;
        }
    };
    

      ----update----

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            s.clear();
            for (int i = 0; i < num.size(); i++) {
                s.insert(num[i]);
            }
            int ans = 0;
            for (int i = 0; i < num.size(); i++) {
                ans = max(ans, bound(num[i], true) + bound(num[i] + 1, false));
            }
            return ans;
        }
    private:
        unordered_set<int> s;
        int bound(int num, bool asc) {
            int cnt = 0;
            for (auto iter = s.find(num); iter != s.end(); iter = s.find(num)) {
                s.erase(iter);
                if (asc) num--; else num++;
                cnt++;
            }
            return cnt;
        }
    };
    

      

  • 相关阅读:
    java中一个类中没有公共的构造方法,则说明不能让外界去new对象。
    PyQt IDE 环境搭建
    移动App开发基本技术面
    创业公司的技术管理
    软件工程师职业道德规范和实践要求
    比较好的刷题网站推荐
    对于程序员在boss直聘求职的建议
    cocospod 安装和使用
    TabBarController和其他view无法建立Relationship segue的原因
    面试与反面试的一些问题
  • 原文地址:https://www.cnblogs.com/x1957/p/3274274.html
Copyright © 2011-2022 走看看