[leetcode] Longest Consecutive Sequence

来源:互联网 发布:淘宝的专营店 编辑:程序博客网 时间:2024/05/02 11:45

From : https://leetcode.com/problems/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>& nums) {        map<int, bool> has;        int len = nums.size();        for(int i=0; i<len; ++i) {            has[nums[i]] = true;        }                int num = 0;        for(int i=0; i<len; ++i) {            int cur = 1;            if(has[nums[i]]) {                // left                for(int k=nums[i]-1;; --k) {                    if(has[k]) {                        ++cur;                        has[k] = false;                    } else{                        break;                    }                }                // right                for(int k=nums[i]+1;; ++k) {                    if(has[k]) {                        ++cur;                        has[k] = false;                    } else{                        break;                    }                }            }            if(cur > num) {                num = cur;            }        }        return num;            }};


0 0
原创粉丝点击