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

     

    class Solution {
    public:
        int longestConsecutive(vector<int> &num) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            unordered_set<int> hash;
            
            for(int i = 0; i < num.size(); i++){
                hash.insert(num[i]);
            }
            
            unordered_set<int>::iterator it;
            int result = 0;
            int tmp_elem;
            int cnt;
            unordered_set<int>::iterator tmp_it;
            
            while(!hash.empty()){
                cnt = 1;
                it = hash.begin();
                
                int elem = *it;
                hash.erase(it);
                
                tmp_elem = elem + 1;
                while((tmp_it = hash.find(tmp_elem)) != hash.end()){
                    cnt++;
                    tmp_elem++;
                    hash.erase(tmp_it);
                }
     
                tmp_elem = elem - 1;
                while((tmp_it = hash.find(tmp_elem)) != hash.end()){
                    cnt++;
                    tmp_elem--;
                    hash.erase(tmp_it);
                }
                result = max(result, cnt);
                
            }
            
            return result;
            
        }
    };


  • 相关阅读:
    随便练习的进制转换
    回顾快速排序
    常用c++函数
    POJ 1163 The Triangle
    HDU 1155 Bungee Jumping
    ZOJ 3861 Valid Pattern Lock
    POJ 1273 Drainage Ditches
    Hrbust 2240 土豪的时代
    POJ 3468 A Simple Problem with Integers
    POJ 1061 青蛙的约会
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3157410.html
Copyright © 2011-2022 走看看