Saturday, August 29, 2015

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.
Runtime: 36 ms

int longestConsecutive(vector<int>& nums) {
        unordered_map<int, int> tmp;
        int maxN = 0;
        for (int i = 0; i != nums.size(); ++i)
        {
            int t = nums[i];
            if (tmp.find(t) != tmp.end())
            {
                continue;
            }
            else
            {
                tmp[t] = t;
                maxN = max(maxN, 1);
            }
            if (tmp.find(t - 1) != tmp.end() && tmp[t-1] < t)
            {
                maxN = max(maxN, t - tmp[t-1] + 1);
                tmp[t] = tmp[t - 1];
                tmp[tmp[t-1]] = t;
            }
            if (tmp.find(t + 1) != tmp.end() && tmp[t+1] > t)
            {
                maxN = max(maxN, tmp[t+1] - tmp[t] + 1);
                int lowerBound = tmp[t];
                tmp[lowerBound] = tmp[t+1];
                tmp[tmp[t+1]] = lowerBound;
            }
        }
        return maxN;
    }

No comments:

Post a Comment