LEETCODE: Longest Consecutive Sequence

来源:互联网 发布:中昌数据千股千评 编辑:程序博客网 时间:2024/06/04 00:33

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.

用map来记录,实际上也就是用map里的hash方法来解决这个问题。

class Solution {public:    int longestConsecutive(vector<int> &num) {        map<int, int> themap;        for(int ii = 0; ii < num.size(); ii ++) {            themap[num[ii]] = 1;        }        int max = 0;        for(int ii = 0; ii < num.size(); ii ++) {            int current = num[ii];            if(themap[current] == 0) continue;            themap[current] = 0;            int len = 1;            // Search to left.            int toleft = current - 1;            while(themap.find(toleft) != themap.end()) {                len ++;                themap[toleft] = 0;                toleft --;            }            // Search to right.            int toright = current + 1;            while(themap.find(toright) != themap.end()) {                len ++;                themap[toright] = 0;                toright ++;            }            if(len > max) {                max = len;            }        }        return max;    }};





0 0
原创粉丝点击