Leetcode-Longest Consecutive Sequence

来源:互联网 发布:黄河商品交易软件 编辑:程序博客网 时间:2024/06/06 12:28

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.

Version 1

class Solution {public:    int longestConsecutive(vector<int>& nums) {        unordered_set<int> mset, tmpset;        for (auto i : nums) {            mset.insert(i);        }        int res = 0, tint = 0;        for (auto i : nums) {            if (tmpset.find(i) != tmpset.end()) continue;            tmpset.insert(i);            tint = 1;            int j = i-1;            while (mset.find(j) != mset.end()) {                tmpset.insert(j);                j--;                tint++;            }            j = i+1;            while (mset.find(j) != mset.end()) {                tmpset.insert(j);                j++;                tint++;            }            if (res < tint) res = tint;        }        return res;    }};

Version 2

use a hash map to store boundary information of consecutive sequence for each element; there 4 cases when a new element i reached:

neither i+1 nor i-1 has been seen: m[i]=1;

both i+1 and i-1 have been seen: extend m[i+m[i+1]] and m[i-m[i-1]] to each other;

only i+1 has been seen: extend m[i+m[i+1]] and m[i] to each other;

only i-1 has been seen: extend m[i-m[i-1]] and m[i] to each other.

int longestConsecutive(vector<int> &num) {    unordered_map<int, int> m;    int r = 0;    for (int i : num) {        if (m[i]) continue;        r = max(r, m[i] = m[i + m[i + 1]] = m[i - m[i - 1]] = m[i + 1] + m[i - 1] + 1);    }    return r;}
0 0
原创粉丝点击