zoukankan      html  css  js  c++  java
  • LeetCode 128 最长连续序列

    本题要求是给出一个无序数组,在数组种找出最长的连续序列,时间复杂度是O(n)。这道题并不难,主要是接触了一个新的数据结构,用哈希表实现的set,查找和插入可以在几乎O(1)的时间完成。遍历整个数组,如果在set种找到比当前数字小1的就跳过(该数不可能是连续序列中最小的数),如果没有找到,就从这个数开始一直向后找比它大1的数,直到找不到停止。统计出最长的连续序列。

    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            int ans = 0;
            unordered_set<int> st;
            for(auto i :nums)
            {
                st.insert(i);
            }
            for(auto i : nums)
            if(!st.count(i-1))
            {
                int cur=i;
                int cnt=1;
                while(st.count(cur+1))
                {
                    cur++;
                    cnt++;
                }
                ans=max(cnt,ans);
            }
            return ans;
        }
    };
    
  • 相关阅读:
    poj 1286
    poj 1815
    poj 3368
    十个利用矩阵乘法解决的经典题目
    poj 1026
    hdu 1394
    poj 3270
    poj 2154
    《重构 改善既有代码的设计》读书笔记2
    Android OpenGL ES: 渐变颜色的三角形
  • 原文地址:https://www.cnblogs.com/ambition-hhn/p/13054149.html
Copyright © 2011-2022 走看看