zoukankan      html  css  js  c++  java
  • Longest Consecutive Sequence 分类: Leetcode(线性表) 2015-02-04 09:54 55人阅读 评论(0) 收藏

    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.

    对于线性表的题目,如果要求复杂度是O(n)的,我只能说,请考虑hash!!!!!!!!!!!!!!!!!!!!!!!

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            unordered_map<int, bool> used;
            int i,j;
            for(i = 0; i < num.size(); i++){
                used[num[i]] = false;
            }
            
            int longest = 0;
            for(i =0; i < num.size(); i++){
                if (used[num[i]]) continue;
                
                int length = 1;
                
                used[num[i]] = true;
                
                for(j = num[i] + 1; used.find(j) != used.end(); ++j){
                    used[j] = true;
                    ++length;
                }
                
                for(j = num[i]-1; used.find(j) != used.end(); --j){
                    used[j] = true;
                    ++length;
                }
                
                longest = max(longest, length);
            }
            return longest;
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    还是java中的编码问题
    java restful api
    编码方式
    LinkedHash
    Zoj 2562 More Divisors (反素数)
    spark复习总结03
    spark复习总结02
    spark复习总结01
    使用二进制解决一个字段代表多个状态的问题
    spark性能调优05-troubleshooting处理
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656959.html
Copyright © 2011-2022 走看看